package common

import "strings"

var replacer *strings.Replacer

func init() {
	trimChars := "0123456789-()/½⅓¼⅕⅙⅐⅛⅑⅔⅖¾⅗⅘"
	tcs := make([]string, len(trimChars)*2)
	for i, c := range trimChars {
		tcs[i*2] = string(c)
		tcs[i*2+1] = ""
	}
	replacer = strings.NewReplacer(tcs...)
}

type List struct {
	Name  string `json:"name"`
	Group string `json:"group"`
	Items []Item `json:"items"`
	// ID is the Mealie API reference for the list.
	ID int `json:"id"`
}

var sortableText map[string]string = map[string]string{}

func (l List) Len() int      { return len(l.Items) }
func (l List) Swap(i, j int) { l.Items[i], l.Items[j] = l.Items[j], l.Items[i] }

func (l List) Less(i, j int) bool {
	var ok bool
	var it, jt string
	li := l.Items[i]
	lit := li.Text
	if it, ok = sortableText[lit]; !ok {
		it = replacer.Replace(strings.ToUpper(lit))
		it = strings.TrimLeft(it, " ")
		sortableText[lit] = it
	}
	lj := l.Items[j]
	ljt := lj.Text
	if jt, ok = sortableText[ljt]; !ok {
		jt = replacer.Replace(strings.ToUpper(ljt))
		jt = strings.TrimLeft(jt, " ")
		sortableText[ljt] = jt
	}
	if !li.Checked {
		if lj.Checked {
			return true
		}
		return it < jt
	}
	if !lj.Checked {
		return false
	}
	return it < jt
}

type Item struct {
	Id       string      `json:"id"`
	Title    string      `json:"title"`
	Text     string      `json:"text"`
	Quantity int         `json:"quantity"`
	Checked  bool        `json:"checked"`
	Size     int64       `json:"size"`
	Data     interface{} `json:"data"`
}

func NewList(name string) List {
	return List{
		ID:    -1,
		Name:  name,
		Items: []Item{},
	}
}
