package app

import (
	"fmt"
	"os"

	"git.sr.ht/~jamesponddotco/acopw-go"
	"github.com/urfave/cli/v2"
	"golang.org/x/term"
)

// RandomAction is the action for the random command.
func RandomAction(c *cli.Context) error {
	var (
		lower     = c.Bool("lowercase")
		upper     = c.Bool("uppercase")
		numbers   = c.Bool("numbers")
		symbols   = c.Bool("symbols")
		generator *acopw.Random
	)

	if !(lower || upper || numbers || symbols) {
		generator = &acopw.Random{
			ExcludedCharset: c.StringSlice("excluded"),
			Length:          int(c.Uint("length")),
			UseLower:        true,
			UseUpper:        true,
			UseNumbers:      true,
			UseSymbols:      true,
		}
	} else {
		generator = &acopw.Random{
			ExcludedCharset: c.StringSlice("excluded"),
			Length:          int(c.Uint("length")),
			UseLower:        lower,
			UseUpper:        upper,
			UseNumbers:      numbers,
			UseSymbols:      symbols,
		}
	}

	var (
		password   = generator.Generate()
		isTerminal = term.IsTerminal(int(os.Stdout.Fd()))
	)

	if isTerminal {
		if _, err := fmt.Fprintln(c.App.Writer, password); err != nil {
			return fmt.Errorf("%w", err)
		}

		return nil
	}

	if _, err := fmt.Fprint(c.App.Writer, password); err != nil {
		return fmt.Errorf("%w", err)
	}

	return nil
}
