package subcmd

import (
	"context"
	"flag"

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

// UpdateService creates a guardian app task definition and updates the service
// with it.
type UpdateService struct {
	*Base
	taskDefinitionArn string
}

// Name implements subcommands
func (cmd UpdateService) Name() string {
	return "update-service"
}

// Synopsis implements subcommands
func (cmd UpdateService) Synopsis() string {
	return "update service with a task definition"
}

// Usage implements subcommands
func (cmd UpdateService) Usage() string {
	return `update-service -env [env] -build-id [build-id] -task-def-arn <task-def-arn>

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

`
}

// SetFlags implements subcommands
func (cmd *UpdateService) SetFlags(f *flag.FlagSet) {
	cmd.Base.SetFlags(f)
	f.StringVar(&cmd.taskDefinitionArn, "task-def-arn", "", "Task definition to update service with.")
}

// Execute implements subcommands
func (cmd UpdateService) 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 UpdateService) execute(ctx context.Context) error {
	if _, err := cmd.ecs.UpdateServiceWithContext(ctx, &ecs.UpdateServiceInput{
		Cluster:        aws.String(cmd.config.ECSClusterName.Get()),
		Service:        aws.String(cmd.config.ECSServiceName.Get()),
		TaskDefinition: aws.String(cmd.taskDefinitionArn),
	}); err != nil {
		return err
	}

	cmd.Logger.Printf("updated service with task: %s", cmd.taskDefinitionArn)
	return nil
}
