// Copyright 2015 Keybase, Inc. All rights reserved. Use of
// this source code is governed by the included BSD license.

package client

import (
	"fmt"

	"golang.org/x/net/context"

	"github.com/keybase/cli"
	"github.com/keybase/client/go/libcmdline"
	"github.com/keybase/client/go/libkb"
	keybase1 "github.com/keybase/client/go/protocol/keybase1"
)

type CmdListTracking struct {
	libkb.Contextified
	assertion string
	filter    string
	json      bool
	verbose   bool
	headers   bool
}

func (s *CmdListTracking) ParseArgv(ctx *cli.Context) error {
	if len(ctx.Args()) == 1 {
		s.assertion = ctx.Args()[0]
	} else if len(ctx.Args()) > 1 {
		return fmt.Errorf("list-following takes at most one argument")
	}

	s.json = ctx.Bool("json")
	s.verbose = ctx.Bool("verbose")
	s.headers = ctx.Bool("headers")
	s.filter = ctx.String("filter")

	return nil
}

func displayTable(g *libkb.GlobalContext, entries []keybase1.UserSummary, verbose bool, headers bool) (err error) {
	tui := g.UI.GetTerminalUI()
	if verbose {
		noun := "users"
		if len(entries) == 1 {
			noun = "user"
		}
		tui.Printf("Following %d %s:\n\n", len(entries), noun)
	}

	var cols []string

	if headers {
		if verbose {
			cols = []string{
				"Username",
				"UID",
				"Link ID",
			}
		} else {
			cols = []string{"Username"}
		}
	}

	i := 0
	rowfunc := func() []string {
		if i >= len(entries) {
			return nil
		}
		entry := entries[i]
		i++

		if !verbose {
			return []string{entry.Username}
		}

		row := []string{
			entry.Username,
			entry.Uid.String(),
			entry.LinkID.String(),
		}
		return row
	}

	libkb.Tablify(tui.OutputWriter(), cols, rowfunc)
	return
}

func displayJSON(g *libkb.GlobalContext, jsonStr string) error {
	tui := g.UI.GetTerminalUI()
	_, err := tui.Printf("%s\n", jsonStr)
	return err
}

func (s *CmdListTracking) Run() error {
	cli, err := GetUserClient(s.G())
	if err != nil {
		return err
	}

	if s.json {
		jsonStr, err := cli.ListTrackingJSON(context.TODO(), keybase1.ListTrackingJSONArg{
			Assertion: s.assertion,
			Filter:    s.filter,
			Verbose:   s.verbose,
		})
		if err != nil {
			return err
		}
		return displayJSON(s.G(), jsonStr)
	}

	ret, err := cli.ListTracking(context.TODO(), keybase1.ListTrackingArg{Filter: s.filter, Assertion: s.assertion})
	if err != nil {
		return err
	}
	return displayTable(s.G(), ret.Users, s.verbose, s.headers)
}

func NewCmdListTracking(cl *libcmdline.CommandLine, g *libkb.GlobalContext) cli.Command {
	return cli.Command{
		Name:         "list-following",
		ArgumentHelp: "<username>",
		Usage:        "List who you or the given user is publicly following",
		Action: func(c *cli.Context) {
			cl.ChooseCommand(&CmdListTracking{Contextified: libkb.NewContextified(g)}, "following", c)
		},
		Flags: []cli.Flag{
			cli.StringFlag{
				Name:  "f, filter",
				Usage: "Provide a regex filter.",
			},
			cli.BoolFlag{
				Name:  "H, headers",
				Usage: "Show column headers.",
			},
			cli.BoolFlag{
				Name:  "j, json",
				Usage: "Output as JSON (default is text).",
			},
			cli.BoolFlag{
				Name:  "v, verbose",
				Usage: "A full dump, with more gory details.",
			},
		},
	}
}

func (s *CmdListTracking) GetUsage() libkb.Usage {
	return libkb.Usage{
		Config: true,
		API:    true,
	}
}
