package configuration

import (
	"code.justin.tv/d8a/buddy/cmd/buddy-cli/data"
	"code.justin.tv/d8a/buddy/lib/alerts"
	"code.justin.tv/d8a/buddy/lib/clusters"
	"code.justin.tv/d8a/buddy/lib/config"
	"code.justin.tv/d8a/buddy/lib/store"
	"github.com/aws/aws-sdk-go/service/cloudwatch"
	"github.com/aws/aws-sdk-go/service/sns"
	"github.com/spf13/cobra"
)

var alertLevel = &cobra.Command{
	Use:   "alert-level [cluster] [level]",
	Short: "Modify level of alerts to provision for the cluster.",
	Long:  "Modify level of alerts to provision for the cluster. Values are: noalarms, minimum, moderate, high, verbose",
	RunE: func(command *cobra.Command, args []string) error {
		if len(data.ConfigureData.Args()) != 1 {
			return command.Usage()
		}

		foundCluster := data.ConfigureData.FoundCluster()
		configFile := data.ConfigureData.ConfigFile()

		//Update the alarm priority
		foundCluster.AlarmPriorityStr = data.ConfigureData.Args()[0]
		err := foundCluster.ParseAlarmPriority()
		if err != nil {
			return command.Usage()
		}

		//Reprovision alarms- first we need to get RDS instances
		configFile.Cluster = make(config.ClusterList, 0)
		configFile.Cluster = append(configFile.Cluster, foundCluster)
		rdsInstances, _, err := clusters.FetchMeta(configFile.Cluster, data.ConfigureData.RdsClient())
		if err != nil {
			return err
		}

		snsClient := sns.New(data.ConfigureData.Session())
		cloudwatchClient := cloudwatch.New(data.ConfigureData.Session())
		priorities := make(map[string]alerts.AlarmPriority)
		for _, instance := range rdsInstances {
			priorities[*instance.DBInstanceIdentifier] = foundCluster.AlarmPriority
		}

		err = store.UpdateAlarmPriority(data.ConfigureData.StoreDB(), foundCluster)
		if err != nil {
			return err
		}

		return alerts.ConfigureAlarms(snsClient, cloudwatchClient, configFile.SandstormTeam, priorities, rdsInstances)
	},
}

func init() {
	ConfigureCmd.AddCommand(alertLevel)
}
