package main

import (
	"fmt"
	"log"
	"sort"

	"github.com/aws/aws-sdk-go/aws"
	"github.com/aws/aws-sdk-go/aws/session"
	"github.com/aws/aws-sdk-go/service/cloudwatch"
)

const awsRegion = "us-west-2"

var streamScheduleParams = Params {
	Operations: []string{
		"BatchGetNextSegment",
		"BatchGetSegments",
		"CreateSchedule",
		"CreateSegment",
		"DeleteSchedule",
		"DeleteSegment",
		"EventbusUserDestroy",
		"GetAutohostChanelForCarousel",
		"GetSchedule",
		"GetSegments",
		"InterruptSchedule",
		"ResumeSchedule",
		"UpdateSegment",
		"ValidateAuthorization",
	},
	Service: "StreamSchedule",
	Stage: "prod",
	Namespace: "StreamSchedule",
}

var autohostServerParams = Params {
	Operations: []string{
		"api/AddList",
		"api/GetList",
		"api/GetSettings",
		"api/HostTarget",
		"api/RemoveList",
		"api/SetList",
		"api/Unhost",
		"api/UpdateSettings",
		"AddToAutohostList",
		"GetAutohostChannelForCarousel",
		"GetAutohostList",
		"GetAutohostSettings",
		"GetEndorsedChannels",
		"RemoveFromAutohostList",
		"SetAutohostList",
		"UpdateAutohostSettings",
	},
	Service: "Autohost Server",
	Stage: "production",
	Namespace: "Autohost Server",
}

func main() {
	err := do(autohostServerParams)
	if err != nil {
		log.Fatalln(err)
	}
}

type Params struct {
	Operations []string
	Service string
	Stage string
	Namespace string
}

func do(params Params) error {
	awsSession, err := session.NewSession(&aws.Config{
		Region: aws.String(awsRegion),
	})
	if err != nil {
		return err
	}

	cw := cloudwatch.New(awsSession)

	for _, op := range params.Operations {
		err = getDepsForOperation(cw, params, op)
		if err != nil {
			return err
		}
	}

	return nil
}

func getDepsForOperation(cw *cloudwatch.CloudWatch, params Params, operation string) error {
	out, err := cw.ListMetrics(&cloudwatch.ListMetricsInput{
		Dimensions: []*cloudwatch.DimensionFilter{
			{
				Name:  aws.String("Operation"),
				Value: aws.String(operation),
			}, {
				Name:  aws.String("Region"),
				Value: aws.String(awsRegion),
			}, {
				Name:  aws.String("Service"),
				Value: aws.String(params.Service),
			}, {
				Name:  aws.String("Stage"),
				Value: aws.String(params.Stage),
			}, {
				Name:  aws.String("Substage"),
				Value: aws.String("primary"),
			},
		},
		MetricName: aws.String("DependencyDuration"),
		Namespace:  aws.String(params.Namespace),
	})
	if err != nil {
		return err
	}
	fmt.Println()
	fmt.Println(operation)

	deps := make([]string, 0)

	for _, metric := range out.Metrics {
		for _, dim := range metric.Dimensions {
			if dim.Name != nil && *dim.Name == "Dependency" && dim.Value != nil {
				deps = append(deps, *dim.Value)
			}
		}
	}

	sort.Strings(deps)
	for _, dep := range deps {
		fmt.Println(fmt.Sprintf("\"%s\",", dep))
	}

	return nil
}
