package cmd

import (
	"fmt"

	"code.justin.tv/cplat/twitchling/cmd/twitchling/format"
	"code.justin.tv/cplat/twitchling/project"
	"github.com/spf13/cobra"
)

var validateJUnitReport string

const (
	junitReportFlag = "junit-report"
)

var validateCmd = &cobra.Command{
	Use:   "validate",
	Short: "validate project.toml and check for errors",
	Long:  ``,
	RunE:  runValidate,
}

func init() {
	rootCmd.AddCommand(validateCmd)
	validateCmd.Flags().StringVarP(&validateJUnitReport, junitReportFlag, "", "", "output a JUnit compatible report file to the specified location")
}

func runValidate(cmd *cobra.Command, args []string) error {
	project, err := project.LoadProject(projectFile)
	if err != nil {
		return fmt.Errorf("failed to load project file %s\n%v", projectFile, err)
	}

	var pass, fail int
	result := project.Validate()
	for _, m := range result.Results {
		if m.Error != nil {
			fail++
			cmd.PrintErrf("--- %s: id: %s, variant: %s\n", format.RedBold("FAIL"), m.ID, m.Variant)
			cmd.PrintErrln(format.FormatError(m.ID, m.Variant, m.Error))
		} else {
			pass++
			cmd.Printf("--- %s: id: %s, variant: %s\n", format.GreenBold("PASS"), m.ID, m.Variant)
		}
	}

	cmd.Printf("DONE Pass: %d, Fail: %d.\n", pass, fail)
	if fail > 0 {
		return fmt.Errorf("found invalid messages in input")
	}

	return nil
}
