package ui

import (
	"image"
	"math"
	"strconv"

	"code.ur.gs/lupine/ordoor/internal/assetstore"
	"code.ur.gs/lupine/ordoor/internal/menus"
)

// A checkbox can be a fancy button
type checkbox struct {
	button

	valueImpl
}

// A slider is harder. Two separate elements to render
type slider struct {
	locator string

	rect image.Rectangle

	baseSpr   *assetstore.Sprite
	clickSpr  *assetstore.Sprite
	sliderSpr *assetstore.Sprite

	hv    bool        // horizontal (false) or vertical (true) slider
	steps map[int]int // A list of valid steps. value:offset

	clickImpl
	mouseImpl
	valueImpl
}

// A checkbox has 3 sprites, and 3 states: unchecked, checked, disabled.
func (d *Driver) buildCheckbox(p *menus.Properties) (*checkbox, *Widget, error) {
	sprites, err := d.menu.Sprites(p.ObjectIdx, p.Share, 3) // unchecked, disabled, checked
	if err != nil {
		return nil, nil, err
	}

	checkbox := &checkbox{
		button: button{
			locator:   p.Locator,
			rect:      sprites[0].Rect.Add(p.Point()),
			baseSpr:   sprites[0], // unchecked
			clickSpr:  sprites[2], // checked
			frozenSpr: sprites[1], // disabled
			hoverImpl: hoverImpl{text: p.Text},
		},
		valueImpl: valueImpl{str: "0"},
	}

	widget := &Widget{
		Locator:       p.Locator,
		Active:        p.Active,
		ownClickables: []clickable{checkbox},
		ownFreezables: []freezable{checkbox},
		ownHoverables: []hoverable{checkbox},
		ownPaintables: []paintable{checkbox},
		ownValueables: []valueable{checkbox},
	}

	return checkbox, widget, nil
}

func (d *Driver) buildSlider(p *menus.Properties) (*slider, *Widget, error) {
	sprites, err := d.menu.Sprites(p.ObjectIdx, p.Share, 3) // base, clicked, slider element
	if err != nil {
		return nil, nil, err
	}

	slider := &slider{
		locator:   p.Locator,
		rect:      sprites[0].Rect.Add(p.Point()),
		baseSpr:   sprites[0],
		clickSpr:  sprites[1],
		sliderSpr: sprites[2],
		hv:        sprites[0].Rect.Dy() > sprites[0].Rect.Dx(), // A best guess
	}

	widget := &Widget{
		Locator:       p.Locator,
		Active:        p.Active,
		ownClickables: []clickable{slider},
		ownMouseables: []mouseable{slider},
		ownPaintables: []paintable{slider},
		ownValueables: []valueable{slider},
	}

	return slider, widget, nil
}

func (c *checkbox) registerMouseClick() {
	if c.value() == "1" { // Click disables
		c.setValue("0")
	} else { // Click enables
		c.setValue("1")
	}
}

func (c *checkbox) regions(tick int) []region {
	if c.isFrozen() {
		return oneRegion(c.bounds().Min, c.frozenSpr.Image)
	}

	if c.value() == "1" {
		return oneRegion(c.bounds().Min, c.clickSpr.Image)
	}

	return oneRegion(c.bounds().Min, c.baseSpr.Image)
}

func (s *slider) id() string {
	return s.locator
}

// The bounds of the slider are the whole thing
func (s *slider) bounds() image.Rectangle {
	return s.rect
}

func (s *slider) registerMouseClick() {
	var value int
	if s.hv {
		value = s.valueFromPix(s.bounds().Min.Y, s.sliderPos().Y)
	} else {
		value = s.valueFromPix(s.bounds().Min.X, s.sliderPos().X)
	}

	s.valueImpl.str = strconv.Itoa(value)

	s.clickImpl.registerMouseClick()
}

func (s *slider) regions(tick int) []region {
	var out []region

	if s.mouseDownState() {
		out = append(out, oneRegion(s.bounds().Min, s.clickSpr.Image)...)
	} else {
		out = append(out, oneRegion(s.bounds().Min, s.baseSpr.Image)...)
	}

	out = append(out, oneRegion(s.sliderPos(), s.sliderSpr.Image)...)

	return out
}

func (s *slider) sliderPos() image.Point {
	if s.hv {
		return s.sliderPosVertical()
	}

	return s.sliderPosHorizontal()
}

func (s *slider) sliderPosHorizontal() image.Point {
	pos := s.bounds().Min

	if s.mouseDownState() {
		pos.X = s.constrainPix(s.bounds().Min.X, s.mouseImpl.pos.X)
	} else {
		pos.X = s.bounds().Min.X + s.offsetFromValue(s.valueInt())
	}

	return pos
}

func (s *slider) sliderPosVertical() image.Point {
	pos := s.bounds().Min

	if s.mouseDownState() {
		pos.Y = s.constrainPix(s.bounds().Min.Y, s.mouseImpl.pos.Y)
	} else {
		pos.Y = s.bounds().Min.Y + s.offsetFromValue(s.valueInt())
	}

	return pos
}

func (s *slider) valueFromPix(start, actual int) int {
	if len(s.steps) == 0 {
		return actual - start
	}

	minDistance := 9999
	var out int

	for value, offset := range s.steps {
		pix := start + offset
		distance := int(math.Abs(float64(actual - pix)))

		if distance < minDistance {
			minDistance = distance
			out = value
		}
	}

	return out
}

func (s *slider) offsetFromValue(value int) int {
	if len(s.steps) == 0 {
		return value
	}

	value = s.constrainValue(value)

	return s.steps[value]
}

func (s *slider) constrainPix(start, actual int) int {
	if len(s.steps) == 0 {
		return actual
	}

	minDistance := 9999
	out := actual

	for _, offset := range s.steps {
		pix := start + offset
		distance := int(math.Abs(float64(actual - pix)))

		if distance < minDistance {
			minDistance = distance
			out = pix
		}
	}

	return out
}
func (s *slider) constrainValue(actual int) int {
	if len(s.steps) == 0 {
		return actual
	}

	minDistance := 9999
	out := actual

	for value, _ := range s.steps {
		distance := int(math.Abs(float64(value - actual)))

		if distance < minDistance {
			minDistance = distance
			out = value
		}
	}

	return out
}

func (s *slider) valueInt() int {
	v, _ := strconv.Atoi(s.valueImpl.value())

	return s.constrainValue(v)
}

func (s *slider) value() string {
	return strconv.Itoa(s.valueInt())
}
