package main

import (
	"context"
	"log"

	"code.justin.tv/websocket-edge/server/internal/autoprof"
	"github.com/aws/aws-sdk-go/aws"
	"github.com/aws/aws-sdk-go/aws/session"

	"go.uber.org/zap"

	"code.justin.tv/websocket-edge/server/internal/environment"
	"code.justin.tv/websocket-edge/server/internal/logs"
	"code.justin.tv/websocket-edge/server/internal/metrics"

	"code.justin.tv/websocket-edge/server/loadtest/launcher"
)

// gitCommit is the short commit hash of the source tree (e.g. "5d85cffc8"). It is set at build time with -ldflags.
var gitCommit string

// The name of the service.
const serviceName = "websocket-edge-loadtest"

func main() {
	var logger logs.Logger
	logger, err := logs.New(environment.IsLocal())
	if err != nil {
		log.Fatalf("Unable to create logger: %v\n", err)
	}
	logger = logger.With(zap.String("gitCommit", gitCommit))

	logFn := func(key string, err error, msg string) {
		logger.Error(msg, zap.Error(err), zap.String("key", key))
	}
	conf := loadConfig(logFn)

	var statter metrics.Statter
	if environment.IsLocal() {
		statter = &metrics.LogStatter{Logger: logger}
	} else {
		statter, err = metrics.New(logger, serviceName, environment.Environment(), gitCommit, conf.awsRegion)
		if err != nil {
			logger.Fatal("Unable to create statter", zap.Error(err))
		}
	}

	session, err := session.NewSession(&aws.Config{
		Region: aws.String("us-west-2"),
	})
	if err != nil {
		logger.Fatal("Unable to create aws session.", zap.Error(err))
	}
	err = autoprof.Go(context.Background(), session, conf.autoprofBucket, func(err error) error {
		logger.Error("Autoprof error", zap.Error(err))
		return err
	})
	if err != nil {
		logger.Warn("Autoprof disabled", zap.Error(err))
	}

	ctx := context.Background()
	launcher.Start(ctx, logger, statter, &launcher.LaunchConf{
		NumMessages:          conf.numMessages,
		NumUsers:             conf.maxUsers,
		SubscriptionInterval: conf.subscriptionInterval,
		MessageInterval:      conf.messageInterval,
		SuiteTimeout:         conf.suiteTimeout,
		UserInterval:         conf.userInterval,
	})
	err = statter.Close()
	if err != nil {
		logger.Error("Error closing statter", zap.Error(err))
	}

	logger.Info("Ending loadtest.")
}
