package historycmd

import (
	"context"
	"flag"
	"os"

	"code.justin.tv/foundation/history-admin/clients/audit"
	"github.com/google/subcommands"
	uuid "github.com/satori/go.uuid"
)

// DumpIDsCmd ...
type DumpIDsCmd struct {
	*BaseCmd

	action   string
	asString bool
}

// Name implements subcommands
func (cmd *DumpIDsCmd) Name() string {
	return "dump-ids"
}

// Synopsis implements subcommands
func (cmd *DumpIDsCmd) Synopsis() string {
	return "dump audit ids to stdout"
}

// Usage implements subcommands
func (cmd *DumpIDsCmd) Usage() string {
	return `dump-ids -action <action> > ids.txt
`
}

// SetFlags implements subcommands
func (cmd *DumpIDsCmd) SetFlags(f *flag.FlagSet) {
	f.StringVar(&cmd.action, "action", "", "action type to filter for")
	f.BoolVar(&cmd.asString, "as-string", false, "dump values as string")
}

// Execute implements subcommands
func (cmd *DumpIDsCmd) Execute(ctx context.Context, f *flag.FlagSet, args ...interface{}) subcommands.ExitStatus {
	if err := cmd.execute(ctx); err != nil {
		cmd.Logger.Error(err)
		return subcommands.ExitFailure
	}
	return subcommands.ExitSuccess
}

func (cmd *DumpIDsCmd) execute(ctx context.Context) error {
	countExecution := cmd.logExecutionCount("scanned", 10000)
	countWritesExecution := cmd.logExecutionCount("wrote", 10000)

	var pageErr error
	if err := cmd.Audit().ScanAudits(ctx, func(a *audit.Audit) bool {
		countExecution()

		if cmd.action != "" && a.Action != cmd.action {
			return true
		}

		var id uuid.UUID
		if id, pageErr = uuid.FromString(a.UUID); pageErr != nil {
			return false
		}

		countWritesExecution()
		if cmd.asString {
			out := id.String() + "," + a.Action + "\n"
			if _, pageErr = os.Stdout.Write([]byte(out)); pageErr != nil {
				return false
			}
		} else {
			if _, pageErr = os.Stdout.Write(id.Bytes()); pageErr != nil {
				return false
			}
		}

		return true
	}); err != nil {
		return err
	}
	return pageErr
}
