package message

import (
	"fmt"

	"code.justin.tv/cplat/twitchling/internal/smartling"
	"code.justin.tv/cplat/twitchling/internal/syntax"
	"code.justin.tv/cplat/twitchling/internal/syntax/ast"
	"code.justin.tv/cplat/twitchling/localization/language"
)

// An instance of Message that is used to produce localized strings.
type Message struct {
	root     []ast.Node
	language language.Tag
}

// Create a new MessageFormat for the specified language and input string.
func New(lang language.Tag, input string) (*Message, error) {
	result, err := syntax.Parse(input)
	if err != nil {
		return nil, fmt.Errorf("failed to create message: %v", err)
	}

	return &Message{result.Root(), lang}, nil
}

// Validates that the given string is a valid ICU MessageFormat string.
// In addition this function checks for various unsupported Smartling features.
func Validate(input string) error {
	result, err := syntax.Parse(input)
	if err != nil {
		return err
	}

	err = smartling.Validate(result)
	if err != nil {
		return err
	}

	return nil
}

func (m *Message) Format(placeholders PlaceholderMap) ([]Fragment, error) {
	formatter := newMessageFormatter(m.language, placeholders)

	return formatter.format(m.root)
}
