package historycmd

import (
	"context"
	"flag"
	"os"

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

// DeleteIDsCmd ...
type DeleteIDsCmd struct {
	*BaseCmd

	threads int
}

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

// Synopsis implements subcommands
func (cmd *DeleteIDsCmd) Synopsis() string {
	return "delete audit ids from stdin"
}

// Usage implements subcommands
func (cmd *DeleteIDsCmd) Usage() string {
	return `delete-ids < ids.txt
`
}

// SetFlags implements subcommands
func (cmd *DeleteIDsCmd) SetFlags(f *flag.FlagSet) {
	f.IntVar(&cmd.threads, "threads", 4, "delete threads to use")
}

// Execute implements subcommands
func (cmd *DeleteIDsCmd) 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 *DeleteIDsCmd) execute(ctx context.Context) error {
	cmd.Audit().DeleteThreads = cmd.threads
	return cmd.Audit().DeleteAudits(ctx, &loggedIDStream{
		IDStream: &audit.ReaderIDStream{Reader: os.Stdin},
		Handler:  cmd.logExecutionCount("id-read", 10000),
	})
}

type loggedIDStream struct {
	IDStream audit.IDStream
	Handler  func()
}

func (r *loggedIDStream) Next(ctx context.Context) (string, bool) {
	r.Handler()
	return r.IDStream.Next(ctx)
}
