package info

import (
	"fmt"
	"os"

	"code.justin.tv/d8a/buddy/cmd/buddy-cli/data"
	"code.justin.tv/d8a/buddy/cmd/buddy-cli/setup"
	"code.justin.tv/d8a/buddy/lib/store"

	"github.com/olekukonko/tablewriter"
	"github.com/spf13/cobra"
)

var clustersCmd = &cobra.Command{
	Use:   "clusters",
	Short: "Show managed database clusters",
	Long:  "Show managed database clusters",
	RunE: func(command *cobra.Command, args []string) error {
		rdsInstance, err := data.RootData.LocateDataStore(false)
		if err != nil {
			return err
		}

		db, err := store.OpenDbConn(rdsInstance, data.RootData.SandstormClient())
		if err != nil {
			return err
		}

		fmt.Println("Retrieving clusters")
		data.RootData.ConfigFile().Cluster, err = store.GetClusters(db)
		if err != nil {
			return err
		}
		fmt.Println("CLusters retrieved")

		table := tablewriter.NewWriter(os.Stdout)
		table.SetHeader([]string{"Name", "Topology", "Identifier", "Database", "Alerts", "Iceman Repo"})
		table.SetBorders(tablewriter.Border{Left: true, Top: false, Right: true, Bottom: false})
		table.SetCenterSeparator("|")

		for _, cluster := range data.RootData.ConfigFile().Cluster {
			var topo string
			if cluster.IsAurora {
				topo = "Cluster"
			} else {
				topo = "Instance"
			}
			table.Append([]string{cluster.Name, topo, cluster.RootIdentifier, cluster.Database, cluster.AlarmPriority.String(), cluster.Repository})
		}
		table.Render()

		return nil
	},
}

func init() {
	setup.RootCmd.AddCommand(clustersCmd)
}
