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
	}

	orgsCmd := cli.Command{
		Name:   "orgs",
		Usage:  "commands related to dev organizations",
		Before: beforeFunc,
		After:  afterFunc,
		Subcommands: []cli.Command{
			{
				Name:  "list",
				Usage: "list all organizations and the teams and projects within",
				Action: func(c *cli.Context) error {
					return printOrgsList(client)
				},
			},
			{
				Name:      "get",
				Usage:     "get information about a particular organization",
				ArgsUsage: "ORGNAME",
				Action: func(c *cli.Context) error {
					orgName := c.Args().Get(0)
					if len(orgName) == 0 {
						return errors.New(
							"organization name argument is required")
					}
					return printOrg(client, orgName)
				},
			},
		},
	}
	app.Commands = append(app.Commands, orgsCmd)
}

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

func printOrg(client *projectmetadata.Client, orgName string) error {
	teamMap, err := client.GetOrg(orgName)
	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
}
