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/clusters/clusterdb"
	"code.justin.tv/d8a/buddy/lib/store"

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

// Here's what this should look like:
// | Name    | Cluster          | User       | Secret                                       | Active |
// ---------------------------------------------------------------------------------------------------
// | friends | cohesion_friends | friends_01 | data-eng/cohesion_friends/staging/friends_01 | true   |
// |         |                  | friends_02 | data-eng/cohesion_friends/staging/friends_02 | false  |
// | chat    | cohesion_chat    | chat_01    | data-eng/cohesion_chat/staging/chat_01       | true   |
// |         |                  | chat_02    | data-eng/cohesion_chat/staging/chat_02       | false  |

var rolePairsCmd = &cobra.Command{
	Use:   "role-pairs [cluster]",
	Short: "Show sandstorm role pairs",
	Long:  "Show sandstorm role pairs",
	RunE: func(command *cobra.Command, args []string) error {
		//Grab a connection to the buddy store & load clusters
		rdsInstance, err := data.RootData.LocateDataStore(false)
		if err != nil {
			return err
		}

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

		data.RootData.ConfigFile().Cluster, err = store.GetClusters(db)
		if err != nil {
			return err
		}

		table := tablewriter.NewWriter(os.Stdout)
		table.SetHeader([]string{"Name", "Cluster", "User", "Secret", "Active"})
		table.SetBorders(tablewriter.Border{Left: true, Top: false, Right: true, Bottom: false})
		table.SetCenterSeparator("|")

		foundCluster := false
		for _, cluster := range data.RootData.ConfigFile().Cluster {
			if len(args) == 0 || cluster.Name == args[0] {
				foundCluster = true

				//Open a connection to the clusters & retrieve all users
				clusterDb, err := clusterdb.OpenDbConn(cluster, data.RootData.SandstormClient(), cluster.SuperUser)
				if err != nil {
					return err
				}

				dbUsers, err := clusterDb.ClusterUsers()
				if err != nil {
					return err
				}

				for _, pair := range cluster.RolePair {
					if len(pair.Users) < 1 {
						table.Append([]string{pair.Name, cluster.Name, "", "", ""})
					} else {
						//Print all users that belong to this role pair- in the first user's line, also print the role pair & cluster name
						name := pair.Name
						clusterName := cluster.Name
						for _, pairUser := range pair.Users {
							canlogin, ok := dbUsers[pairUser.Name]
							table.Append([]string{name, clusterName, pairUser.Name, pairUser.Secret, fmt.Sprintf("%t", canlogin && ok)})
							name = ""
							clusterName = ""
						}
					}
				}
			}
		}

		if foundCluster {
			table.Render()
		} else if len(args) > 0 {
			return fmt.Errorf("There is no cluster named %s.  Did you forget to tag your instances?", args[0])
		}

		return nil
	},
}

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