package splashmenu

import (
	"cosmos/diego/groovy"
	splashmenu "cosmos/diego/groovy/examples/splashmenu/fonts"
	"image/color"
	"math"
	"strconv"

	"github.com/hajimehoshi/ebiten/v2"
	"github.com/hajimehoshi/ebiten/v2/inpututil"
	"github.com/hajimehoshi/ebiten/v2/text"
)

var (
	backgroundBaseColor color.RGBA
)

func init() {
	backgroundBaseColor = color.RGBA{0x33, 0x33, 0x99, 0xFF}
}

type Menu struct {
	Dimensions    groovy.Area
	bgcolor       color.RGBA
	increment     int
	options       map[int]MenuOption
	events        map[groovy.SceneEvent]func()
	menuSelection uint
}

func NewMenu() Menu {
	return Menu{
		bgcolor: backgroundBaseColor,
		events:  make(map[groovy.SceneEvent]func()),
	}
}

func (m *Menu) Update() error {
	m.increment++

	var keysPressed []ebiten.Key
	keysPressed = inpututil.AppendPressedKeys(keysPressed[:0])

	for idx, o := range m.options {
		if m.events[o.SelectionEvent] != nil {
			for _, k := range keysPressed {
				if k == o.Mapping {
					m.menuSelection = uint(idx)
					m.events[o.SelectionEvent]()
				}
			}
		}
	}

	//m.UpdateNoise()
	colorOffset := uint8(int(math.Sin(float64(m.increment)/60) * 25))

	m.bgcolor.R = (colorOffset + backgroundBaseColor.R) % 0xFF
	m.bgcolor.G = (colorOffset + backgroundBaseColor.G) % 0xFF
	m.bgcolor.B = (colorOffset + backgroundBaseColor.B) % 0xFF

	return nil
}

func (m *Menu) Draw(screen *ebiten.Image) {
	screen.Fill(m.bgcolor)
	text.Draw(screen, "menu", splashmenu.SplashFont.Title, 40, 40, color.White)

	m.RenderMetadata(screen)
	m.RenderMenu(screen)
}

func (m *Menu) SetEventHandler(event groovy.SceneEvent, f func()) {
	m.events[event] = f
}

// sets sene dimensions
func (m *Menu) SetDimensions(a groovy.Area) {
	m.Dimensions = a
}

func (m *Menu) RenderMetadata(screen *ebiten.Image) {
	bgcolor := " 0x" + strconv.FormatUint(uint64(m.bgcolor.R), 16) + " 0x" + strconv.FormatUint(uint64(m.bgcolor.G), 16) + " 0x" + strconv.FormatUint(uint64(m.bgcolor.B), 16)
	text.Draw(screen, bgcolor, splashmenu.SplashFont.Menu, 40, 700, color.White)
}

func (m *Menu) SetOptions(options map[int]MenuOption) {
	m.options = make(map[int]MenuOption)

	for k, v := range options {
		m.options[k] = v
	}
}

func (m *Menu) RenderMenu(screen *ebiten.Image) {

	var offset int = 20

	screen.Set(m.Dimensions.Width/2, m.Dimensions.Height/2, color.RGBA{0xFF, 0x00, 0x00, 0xFF})

	for k, v := range m.options {
		m.options[k] = v
		text.Draw(screen, strconv.Itoa(k)+": "+v.Description, splashmenu.SplashFont.Menu, 40, 60+offset*k, color.White)
	}

}

func (m *Menu) GetMenuSelection() uint {
	return m.menuSelection
}
