/*
Copyright © Brian Buller <brian@bullercodeworks.com>

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
package widgets

import (
	"fmt"

	wh "git.bullercodeworks.com/brian/tcell-widgets/helpers"
	"github.com/gdamore/tcell"
)

type Menu struct {
	id       string
	label    string
	style    tcell.Style
	active   bool
	visible  bool
	tabbable bool
	x, y     int
	w, h     int

	menuType     MenuType
	cursor       int
	items        []*MenuItem
	disabled     []bool
	onPressed    func() bool
	manualExpand bool
	expanded     bool
	vimMode      bool

	keyMap KeyMap
}

type MenuType int

const (
	MenuTypeH = MenuType(iota)
	MenuTypeV
)

var _ Widget = (*Menu)(nil)

func NewMenu(id string, style tcell.Style) *Menu {
	ret := &Menu{}
	ret.Init(id, style)
	return ret
}

func (w *Menu) Init(id string, style tcell.Style) {
	w.id = id
	w.style = style
	w.visible = true
	w.keyMap = NewKeyMap(map[tcell.Key]func(ev *tcell.EventKey) bool{
		tcell.KeyRight: w.MoveRight,
		tcell.KeyLeft:  w.MoveLeft,
		tcell.KeyUp:    w.MoveUp,
		tcell.KeyDown:  w.MoveDown,
		tcell.KeyEnter: func(ev *tcell.EventKey) bool {
			if w.onPressed != nil {
				return w.onPressed()
			}
			return false
		},
	})
	w.tabbable = true
}
func (w *Menu) Id() string { return w.id }
func (w *Menu) HandleResize(ev *tcell.EventResize) {
	w.w, w.h = ev.Size()

	// w.w = wh.Min(w.w, w.WantW())
	// w.h = wh.Min(w.h, w.WantH())

	// TODO: Trickle-down HandleResize
}

func (w *Menu) HandleKey(ev *tcell.EventKey) bool {
	if !w.active {
		return false
	} else if w.items[w.cursor].HandleKey(ev) {
		// See if the active menuitem consumes this event
		return true
	} else if ok := w.keyMap.Handle(ev); ok {
		// Otherwise see if we handle it
		return true
	}
	// See if we can find an item that matches the key pressed
	return false
}
func (w *Menu) HandleTime(ev *tcell.EventTime) {}
func (w *Menu) Draw(screen tcell.Screen) {
	switch w.menuType {
	case MenuTypeH:
		w.drawHMenu(screen)
	case MenuTypeV:
		w.drawVMenu(screen)
	}
}

func (w *Menu) drawHMenu(screen tcell.Screen) {
	st := w.style
	if w.active {
		st = w.style.Reverse(true)
	}
	x, y := w.x, w.y
	if len(w.label) > 0 {
		wh.DrawText(x, y, w.label, st, screen)
		x = x + len(w.label) + 2
	}
	x += 2
	if w.expanded || (w.active && !w.manualExpand) {
		// TODO: Use DrawOffset?
		for i := range w.items {
			w.items[i].SetActive(w.active && w.cursor == i)
			w.items[i].SetPos(Coord{X: x, Y: y})
			w.items[i].Draw(screen)
			x += w.items[i].WantW() + 2
		}
	}
}

func (w *Menu) drawVMenu(screen tcell.Screen) {
	if !w.visible {
		return
	}
	x, y := w.x, w.y
	wW, wH := w.WantW(), w.WantH()
	st := w.style
	if w.active {
		st = w.style.Reverse(true)
		wh.TitledBorderFilled(x-1, y, x+w.WantW(), y+w.WantH(), w.label, wh.BRD_CSIMPLE, w.style, screen)
	}
	wh.DrawText(w.x, w.y, w.label, st, screen)
	if w.expanded || (w.active && !w.manualExpand) {
		// TODO: Use DrawOffset?
		for i := range w.items {
			w.items[i].SetActive(w.active && w.cursor == i)
			w.items[i].SetSize(Coord{X: wW, Y: wH})
			w.items[i].SetPos(Coord{X: x, Y: y})
			w.items[i].Draw(screen)
			y++
		}
		y++
	}
}
func (w *Menu) Active() bool       { return w.active }
func (w *Menu) SetActive(a bool)   { w.active = a }
func (w *Menu) Visible() bool      { return w.visible }
func (w *Menu) SetVisible(a bool)  { w.visible = a }
func (w *Menu) SetX(x int)         { w.x = x }
func (w *Menu) SetY(y int)         { w.y = y }
func (w *Menu) GetX() int          { return w.x }
func (w *Menu) GetY() int          { return w.y }
func (w *Menu) GetPos() Coord      { return Coord{X: w.x, Y: w.y} }
func (w *Menu) SetPos(c Coord)     { w.x, w.y = c.X, c.Y }
func (w *Menu) SetW(x int)         { w.w = x }
func (w *Menu) SetH(y int)         { w.h = y }
func (w *Menu) GetW() int          { return w.w }
func (w *Menu) GetH() int          { return w.y }
func (w *Menu) SetSize(c Coord)    { w.w, w.h = c.X, c.Y }
func (w *Menu) Focusable() bool    { return true }
func (w *Menu) SetTabbable(b bool) { w.tabbable = b }
func (w *Menu) Tabbable() bool     { return w.tabbable }

func (w *Menu) WantW() int {
	var maxW int
	for i := range w.items {
		if w.items[i].WantW() > maxW {
			maxW = w.items[i].WantW()
		}
	}
	if maxW < len(w.label) {
		maxW = len(w.label)
	}
	return maxW
}

func (w *Menu) WantH() int {
	if w.menuType == MenuTypeH {
		return 1
	} else {
		var ret int
		if len(w.label) > 0 {
			ret = 1
		}
		return ret + len(w.items)
	}
}

func (w *Menu) MinW() int {
	labels := []string{w.label}
	for i := range w.items {
		labels = append(labels, w.items[i].label)
	}
	switch w.menuType {
	case MenuTypeH:
		wrk := 0
		for i := range labels {
			wrk += len(labels[i])
		}
		return wrk
	case MenuTypeV:
		return wh.Longest(labels)
	}
	return 0
}

func (w *Menu) MinH() int {
	switch w.menuType {
	case MenuTypeH:
		return 1
	case MenuTypeV:
		if len(w.label) > 0 {
			return 1 + len(w.items)
		}
		return len(w.items)
	}
	return 0
}
func (w *Menu) SetType(tp MenuType) { w.menuType = tp }
func (w *Menu) SetLabel(lbl string) { w.label = lbl }
func (w *Menu) SetFocusable(f bool) {}

func (w *Menu) GetItem(idx int) *MenuItem {
	if len(w.items) > idx {
		return w.items[idx]
	}
	return nil
}
func (w *Menu) SetOnPressed(p func() bool) { w.onPressed = p }
func (w *Menu) AddItems(iL ...*MenuItem) {
	var maxW int
	for i := range iL {
		if iL[i].WantW() > maxW {
			maxW = iL[i].WantW()
		}
		w.items = append(w.items, iL[i])
	}
	w.SetW(maxW)
}

func (w *Menu) RemoveItems(iL ...*MenuItem) {
	var wrk []*MenuItem
	for i := range w.items {
		var skip bool
		for j := range iL {
			if w.items[i] == iL[j] {
				skip = true
				break
			}
		}
		if skip {
			continue
		}
		wrk = append(wrk, w.items[i])
	}
	w.items = wrk
}

func (w *Menu) MoveRight(ev *tcell.EventKey) bool {
	if w.menuType != MenuTypeH {
		return false
	}
	w.cursor = (w.cursor + 1) % len(w.items)
	return true
}

func (w *Menu) MoveLeft(ev *tcell.EventKey) bool {
	if w.menuType != MenuTypeH {
		return false
	}
	w.cursor = (w.cursor - 1 + len(w.items)) % len(w.items)
	return true
}

func (w *Menu) MoveUp(ev *tcell.EventKey) bool {
	if w.menuType != MenuTypeV {
		return false
	}
	w.cursor = (w.cursor - 1 + len(w.items)) % len(w.items)
	return true
}

func (w *Menu) MoveDown(ev *tcell.EventKey) bool {
	if w.menuType != MenuTypeV {
		return false
	}
	w.cursor = (w.cursor + 1) % len(w.items)
	return true
}

func (w *Menu) CreateMenuItem(lbl string, do func() bool, subItems ...*MenuItem) *MenuItem {
	d := NewMenuItem(fmt.Sprintf("menuitem-%s", lbl), tcell.StyleDefault)
	d.SetLabel(lbl)
	d.SetOnPressed(do)
	if len(subItems) > 0 {
		d.AddItems(subItems...)
	}
	return d
}
