package euls

import (
	"encoding/json"
	"errors"

	"github.com/aws/aws-sdk-go/aws"
	"github.com/aws/aws-sdk-go/service/mobileanalytics"
)

var (
	errNilConfig = errors.New("config cannot be nil")
)

type eventPutter interface {
	SetConfig(config *Config) error
	PutEvent(event *mobileanalytics.Event) (*mobileanalytics.PutEventsOutput, error)
	Close() error
}

type syncEventPutter struct {
	clientContextJSON []byte
	service           *mobileanalytics.MobileAnalytics
}

func (ep *syncEventPutter) SetConfig(config *Config) error {
	if config == nil {
		return errNilConfig
	}

	session, err := newSession(*config)
	if err != nil {
		return err
	}

	context := newContext(*config)
	ccB, err := json.Marshal(&context)
	if err != nil {
		return err
	}

	ep.clientContextJSON = ccB

	ep.service = mobileanalytics.New(session)
	return nil
}

func (ep *syncEventPutter) PutEvent(event *mobileanalytics.Event) (*mobileanalytics.PutEventsOutput, error) {
	if ep.service == nil {
		return nil, nil
	}

	input := &mobileanalytics.PutEventsInput{
		ClientContext: aws.String(string(ep.clientContextJSON)), // Required
		Events: []*mobileanalytics.Event{ // Required
			event,
		},
	}

	return ep.service.PutEvents(input)
}

func (ep *syncEventPutter) Close() error {
	return nil
}
