package alui

import (
	"opslag.de/schobers/allg5"
	"opslag.de/schobers/geom"
)

type Fonts struct {
	fonts map[string]*allg5.Font
}

type FontDescription struct {
	Path string
	Size int
	Name string
}

func NewFonts() *Fonts {
	return &Fonts{map[string]*allg5.Font{}}
}

func (f *Fonts) Destroy() {
	for _, font := range f.fonts {
		font.Destroy()
	}
	f.fonts = nil
}

func (f *Fonts) Draw(font string, left, top float32, color allg5.Color, text string) {
	f.DrawFont(f.Get(font), left, top, color, text)
}

func (f *Fonts) DrawAlign(font string, left, top, right float32, color allg5.Color, align allg5.HorizontalAlignment, text string) {
	f.DrawAlignFont(f.Get(font), left, top, right, color, align, text)
}

func (f *Fonts) DrawAlignFont(font *allg5.Font, left, top, right float32, color allg5.Color, align allg5.HorizontalAlignment, text string) {
	switch align {
	case allg5.AlignCenter:
		center, top := geom.Round32(.5*(left+right)), geom.Round32(top)
		font.Draw(center, top, color, allg5.AlignCenter, text)
	case allg5.AlignRight:
		right, top = geom.Round32(right), geom.Round32(top)
		font.Draw(right, top, color, allg5.AlignRight, text)
	default:
		left, top = geom.Round32(left), geom.Round32(top)
		font.Draw(left, top, color, allg5.AlignLeft, text)
	}
}

func (f *Fonts) DrawCenter(font string, center, top float32, color allg5.Color, text string) {
	f.DrawCenterFont(f.Get(font), center, top, color, text)
}

func (f *Fonts) DrawCenterFont(font *allg5.Font, center, top float32, color allg5.Color, text string) {
	f.DrawAlignFont(font, center, top, center, color, allg5.AlignCenter, text)
}

func (f *Fonts) DrawFont(font *allg5.Font, left, top float32, color allg5.Color, text string) {
	left, top = geom.Round32(left), geom.Round32(top)
	font.Draw(left, top, color, allg5.AlignLeft, text)
}

func (f *Fonts) Len() int { return len(f.fonts) }

func (f *Fonts) Load(path string, size int, name string) error {
	font, err := allg5.LoadTTFFont(path, size)
	if err != nil {
		return err
	}
	if old := f.fonts[name]; old != nil {
		old.Destroy()
	}
	f.fonts[name] = font
	return nil
}

func (f *Fonts) LoadFonts(descriptions ...FontDescription) error {
	for _, desc := range descriptions {
		err := f.Load(desc.Path, desc.Size, desc.Name)
		if err != nil {
			return err
		}
	}
	return nil
}

func (f *Fonts) Get(name string) *allg5.Font {
	if name == "" {
		return f.Get("default")
	}
	return f.fonts[name]
}
