package domain

import (
	"strings"

	"golang.org/x/text/language"
	"golang.org/x/text/language/display"

	"source.toby3d.me/toby3d/home/internal/common"
)

type Language struct {
	code string
	lang string
	name string
	dir  Direction
}

var LanguageUnd Language = Language{} // "und"

func NewLanguage(raw string) Language {
	tag, err := language.BCP47.Parse(raw)
	if err != nil || tag == language.Und {
		return LanguageUnd
	}

	out := Language{
		code: tag.String(),
		dir:  DirectionLeftToRight,
		name: strings.ToLower(display.Self.Name(tag)),
	}

	switch tag {
	case language.Arabic, language.Persian, language.Hebrew, language.Urdu:
		out.dir = DirectionRightToLeft
	}

	base, _ := tag.Base()
	out.lang = base.String()

	return out
}

func (l Language) Lang() string {
	return l.lang
}

func (l Language) Code() string {
	return l.code
}

func (l Language) Dir() Direction {
	return l.dir
}

func (l Language) Name() string {
	return l.name
}

func (l Language) String() string {
	if l.code != "" {
		return l.code
	}

	return common.Und
}

func (l Language) GoString() string {
	return "domain.Language(" + l.String() + ")"
}
