package euls

import (
	"sync"

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

type asyncEventPutter struct {
	events chan *mobileanalytics.Event
	done   chan struct{}

	eventPutter eventPutter

	initOnce          sync.Once
	processEventsOnce sync.Once
}

func (ep *asyncEventPutter) init() {
	if ep.events == nil {
		ep.events = make(chan *mobileanalytics.Event, 100)
	}

	if ep.done == nil {
		ep.done = make(chan struct{}, 0)
	}
}

func (ep *asyncEventPutter) SetConfig(config *Config) error {
	if ep.eventPutter == nil {
		return nil
	}

	err := ep.eventPutter.SetConfig(config)
	if err == nil {
		ep.init()
		ep.processEventsOnce.Do(func() {
			go ep.processEvents()
		})
	}

	return err
}

func (ep *asyncEventPutter) PutEvent(event *mobileanalytics.Event) (*mobileanalytics.PutEventsOutput, error) {
	ep.init()

	ep.events <- event
	return nil, nil
}

func (ep *asyncEventPutter) Close() error {
	if ep.events == nil {
		return nil
	}

	close(ep.events)
	<-ep.done
	return nil
}

func (ep *asyncEventPutter) processEvents() {
	for event := range ep.events {
		_, err := ep.eventPutter.PutEvent(event)
		if err != nil {
			logger.Println("failed to send events:", err)
		}
	}

	close(ep.done)
}
