package main

import (
	"math/rand"
	"os"
	"strings"
	"time"

	"github.com/rs/zerolog"
	"github.com/rs/zerolog/log"
	"github.com/spf13/pflag"

	"covergen/pkg/covergen"
)

var colors = []string{"red", "blue", "yellow", "green"}
var colorMap = map[string]covergen.Color{
	"red":    {255, 85, 0},
	"blue":   {59, 180, 255},
	"yellow": {255, 230, 0},
	"green":  {76, 177, 110},
}

var number = pflag.StringP("number", "n", "", "Invoice or quotation number")
var customer = pflag.StringP("customer", "c", "", "Customer name for cover")
var numberPrefix = pflag.String("number-prefix", "offerte", "Prefix to use for number")
var color = pflag.String("color", "random", "Selects a color to use for the grid highlight. Valid choices: ['random', 'red', 'blue', 'yellow', 'green']")
var output = pflag.StringP("output", "o", "cover.pdf", "File to output to")

func init() {
	log.Logger = zerolog.New(zerolog.ConsoleWriter{Out: os.Stderr, TimeFormat: time.RFC3339}).With().Timestamp().Logger()
	pflag.Parse()

	if *number == "" {
		log.Error().Msg("Missing (invoice) number flag")
		pflag.Usage()
		os.Exit(1)
	}

	if *customer == "" {
		log.Error().Msg("Missing customer name flag")
		pflag.Usage()
		os.Exit(1)
	}

	if *color != "random" {
		if _, ok := colorMap[*color]; !ok {
			log.Error().Msgf("Color %s is not defined", *color)
			pflag.Usage()
			os.Exit(1)
		}
	}

	if *output == "" {
		log.Error().Msg("Invalid output flag")
		pflag.Usage()
		os.Exit(1)
	}
}

func main() {
	rand.Seed(time.Now().UnixNano())

	var chosenColor covergen.Color
	if *color == "random" {
		chosenColor = colorMap[colors[rand.Intn(len(colors))]]
	} else {
		chosenColor = colorMap[*color]
	}

	*customer = strings.ReplaceAll(*customer, "\\n", "\n")

	pdf, err := covergen.GenerateInvoice(covergen.CoverSettings{
		Number:       *number,
		NumberPrefix: *numberPrefix,
		CustomerName: *customer,
		HLColor:      chosenColor,
	})

	if err != nil {
		log.Fatal().Err(err).Msg("Failed to render invoice")
	}

	if err := pdf.OutputFileAndClose(*output); err != nil {
		log.Fatal().Err(err).Msg("Failed to write invoice to disk")
	}
}
