package ui

import (
	rl "github.com/gen2brain/raylib-go/raylib"
)

type OnSelectCallback func()

type Menu struct {
	selected int
	entries  []Widget
	onSelect OnSelectCallback
}

func NewMenu(entries []Widget) *Menu {
	return &Menu{
		entries:  entries,
		onSelect: func() {},
	}
}

func (menu *Menu) OnSelect(callback OnSelectCallback) *Menu {
	menu.onSelect = callback
	return menu
}

func (menu Menu) Entries() []Widget {
	return menu.entries
}

func (menu *Menu) Select(index int) {
	if index >= 0 && index < len(menu.entries) {
		menu.selected = index
		menu.onSelect()
	}
}

func (menu Menu) Selected() Widget {
	return menu.entries[menu.selected]
}

func (menu Menu) IsSelected(index int) bool {
	return menu.selected == index
}

func (menu *Menu) Next() {
	menu.Select(menu.selected + 1)
}

func (menu *Menu) Previous() {
	menu.Select(menu.selected - 1)
}

func (menu *Menu) HandleInput() {
	if rl.IsKeyPressed(rl.KeyDown) {
		menu.Next()
	} else if rl.IsKeyPressed(rl.KeyUp) {
		menu.Previous()
	} else {
		menu.Selected().HandleInput()
	}
}
