package format

import (
	"fmt"
	"strings"

	"code.justin.tv/cplat/twitchling/internal/syntax"
)

func FormatError(id string, variant string, err error) string {
	switch e := err.(type) {
	case *syntax.ParseError:
		return formatParseError(id, variant, e)
	}

	return formatOtherError(err)
}

func formatOtherError(err error) string {
	return fmt.Sprint(
		Red("error: %s\n", err.Error()),
	)
}

func formatParseError(id string, variant string, err *syntax.ParseError) string {
	helpMessage := ""
	if err.Help() != "" {
		helpMessage = fmt.Sprintf(" help: %s", err.Help())
	}

	return fmt.Sprint(
		Red("error: %s\n", err.Message()),
		fmt.Sprintf("---> id: %s, variant: %s, line: %d, column: %d\n", id, variant, err.StartLine()+1, err.StartColumn()+1),
		// TODO: Assert len(context) > 0
		fmt.Sprintf("%-6d| %s\n", err.StartLine()+1, err.Context()[0]),
		fmt.Sprintf("        %s%s%s",
			strings.Repeat(" ", err.StartColumn()),
			strings.Repeat("^", (err.EndColumn()-err.StartColumn()+1)),
			helpMessage,
		),
		"\n",
	)
}
