package subcmd

import (
	"context"
	"flag"
	"fmt"

	"github.com/aws/aws-sdk-go/aws"
	"github.com/aws/aws-sdk-go/service/ecs"
	"github.com/google/subcommands"
)

// CreateTask creates a guardian app task definition
type CreateTask struct {
	*Base
}

// Name implements subcommands
func (cmd CreateTask) Name() string {
	return "create-task"
}

// Synopsis implements subcommands
func (cmd CreateTask) Synopsis() string {
	return "create a ecs task definition"
}

// Usage implements subcommands
func (cmd CreateTask) Usage() string {
	return `create-task -env [env] -build-id [build-id]

This relies on a docker image with [build-id] is already pushed up to the
internal docker repo.

`
}

// Execute implements subcommands
func (cmd CreateTask) Execute(ctx context.Context, f *flag.FlagSet, args ...interface{}) subcommands.ExitStatus {
	if err := cmd.init(ctx); err != nil {
		cmd.Logger.Print(err)
		return subcommands.ExitFailure
	}

	if err := cmd.execute(ctx); err != nil {
		cmd.Logger.Print(err)
		return subcommands.ExitFailure
	}

	return subcommands.ExitSuccess
}

func (cmd CreateTask) execute(ctx context.Context) error {
	taskDefinitionArn, err := cmd.createTaskDefinition(ctx)
	if err != nil {
		return err
	}
	fmt.Print(taskDefinitionArn)
	return nil
}

func (cmd CreateTask) createTaskDefinition(ctx context.Context) (string, error) {
	out, err := cmd.ecs.RegisterTaskDefinitionWithContext(ctx, &ecs.RegisterTaskDefinitionInput{
		ContainerDefinitions: []*ecs.ContainerDefinition{
			{
				Command: aws.StringSlice([]string{
					"beefcake", "serve",
					"-addr", fmt.Sprintf(":%d", cmd.config.TaskContainerPort.Get()),
					"-env", cmd.env,
				}),
				Image:     aws.String("docker.internal.justin.tv/beefcake/server:" + cmd.buildID),
				Essential: aws.Bool(true),
				Name:      aws.String("app"),
				LogConfiguration: &ecs.LogConfiguration{
					LogDriver: aws.String("awslogs"),
					Options: map[string]*string{
						"awslogs-group":         aws.String(cmd.config.TaskLogGroup.Get()),
						"awslogs-region":        aws.String(cmd.config.AWSRegion.Get()),
						"awslogs-stream-prefix": aws.String(cmd.config.TaskLogStreamPrefix.Get()),
					},
				},
				PortMappings: []*ecs.PortMapping{
					{ContainerPort: aws.Int64(cmd.config.TaskContainerPort.Get())},
				},
			},
		},
		Cpu:              aws.String("256"),
		ExecutionRoleArn: aws.String(cmd.config.TaskExecutionRoleArn.Get()),
		Family:           aws.String(cmd.config.TaskFamily.Get()),
		Memory:           aws.String("1024"),
		NetworkMode:      aws.String("bridge"),
		TaskRoleArn:      aws.String(cmd.config.TaskServiceRoleArn.Get()),
	})
	if err != nil {
		return "", err
	}
	return aws.StringValue(out.TaskDefinition.TaskDefinitionArn), nil
}
