package main

import (
	"errors"
	"fmt"

	log "github.com/Sirupsen/logrus"
	"github.com/urfave/cli"

	"code.justin.tv/dta/rockpaperscissors/client/projectmetadata"
)

func init() {
	var client *projectmetadata.Client
	beforeFunc := func(c *cli.Context) error {
		var err error
		client, err = projectmetadata.NewClient(c.GlobalString("rps-addr"))
		if err != nil {
			return err
		}
		return nil
	}
	afterFunc := func(c *cli.Context) error {
		if client == nil {
			return nil
		}
		if err := client.Close(); err != nil {
			log.Error(err)
		}
		return nil
	}

	teamsCmd := cli.Command{
		Name:   "teams",
		Usage:  "commands related to development teams",
		Before: beforeFunc,
		After:  afterFunc,
		Subcommands: []cli.Command{
			{
				Name:  "list",
				Usage: "list all teams and the projects within",
				Action: func(c *cli.Context) error {
					return printTeamsList(client)
				},
			},
			{
				Name:      "get",
				Usage:     "get information about a particular team",
				ArgsUsage: "TEAMNAME",
				Action: func(c *cli.Context) error {
					teamName := c.Args().Get(0)
					if len(teamName) == 0 {
						return errors.New("team name argument is required")
					}
					return printTeam(client, teamName)
				},
			},
		},
	}
	app.Commands = append(app.Commands, teamsCmd)
}

func printTeamsList(client *projectmetadata.Client) error {
	teamMap, err := client.ListTeams(false)
	if err != nil {
		return err
	}
	for teamName, projects := range teamMap {
		fmt.Printf("%s:\n", teamName)
		for _, project := range projects {
			fmt.Printf("  %s: %s\n", project.GetProjectId(), project.GetProjectName())
		}
	}
	return nil
}

func printTeam(client *projectmetadata.Client, teamName string) error {
	projects, err := client.GetTeam(teamName)
	if err != nil {
		return err
	}
	for _, project := range projects {
		fmt.Printf("%s: %s\n", project.GetProjectId(), project.GetProjectName())
	}
	return nil
}
