package events

import (
	"time"

	"code.justin.tv/sse/malachai/pkg/config"
	"code.justin.tv/sse/malachai/pkg/internal/closer"
	"code.justin.tv/sse/malachai/pkg/internal/fhevent"
	"code.justin.tv/sse/malachai/pkg/log"
	"github.com/aws/aws-sdk-go/aws"
	"github.com/aws/aws-sdk-go/aws/session"
	"github.com/aws/aws-sdk-go/service/firehose"
)

// NewEventLogger constructs an in memory event logger
func NewEventLogger(cfg Config, logger log.S2SLogger) (client *Client, err error) {
	if logger == nil {
		logger = &log.NoOpLogger{}
	}

	client = &Client{
		Closer: closer.New(),
		Logger: logger,
		cfg:    cfg,
	}

	err = client.InitBatchShipper(nil)
	return
}

// InitBatchShipper initializes the BatchShipper with the provided aws config base
func (c *Client) InitBatchShipper(awsConfigBase *aws.Config) error {
	err := c.cfg.fillDefaults()
	if err != nil {
		return err
	}

	sess, err := session.NewSession(config.AWSConfig(awsConfigBase, c.cfg.firehoseRegion(), c.cfg.firehoseLoggerRoleArn()))
	if err != nil {
		return err
	}

	bs := &batchShipper{
		Closer: c.Closer,
		EventWriter: &fhevent.Client{
			FirehoseAPI: firehose.New(sess),
			Logger:      c.Logger,
		},
		Logger:                     c.Logger,
		MaxItemsInBuffer:           c.cfg.maxItemsInBuffer(),
		BatchFlushRate:             time.Minute,
		ItemFlushRate:              time.Minute,
		FirehoseDeliveryStreamName: c.cfg.firehoseDeliveryStreamName(),
		MaxFirehoseFlushTime:       time.Minute,
		FirehoseRetryRate:          100 * time.Millisecond,
	}

	bs.init()

	c.BatchShipper = bs
	return nil
}
