package main

import (
	"go.wit.com/dev/andlabs/ui"
	_ "go.wit.com/dev/andlabs/ui/winmanifest"

	"go.wit.com/log"
	"go.wit.com/gui/widget"
)

func (p *node) newDropdown(n *node) {
	newt := new(guiWidget)
	log.Log(INFO, "gui.Toolbox.newDropdown() START", n.progname)

	cb := ui.NewCombobox()
	newt.uiCombobox = cb
	newt.uiControl = cb

	// initialize the index
	newt.c = 0
	newt.val = make(map[int]string)

	cb.OnSelected(func(spin *ui.Combobox) {
		i := spin.Selected()
		if (newt.val == nil) {
			log.Log(ERROR, "make map didn't work")
			n.value = "map did not work. ui.Combobox error"
		} else {
			n.value = newt.val[i]
		}
		n.doUserEvent()
	})


	n.tk = newt
	p.place(n)

	if n.strings == nil {return}
	// add the initial dropdown entries
	for i, s := range n.strings {
		log.Warn("add dropdown: add entries on create", n.progname, i, s)
		n.addDropdownName(s)
	}
	cur := widget.GetString(n.value)
	log.Warn("add dropdown: set default value on create", n.progname, cur)
	n.setDropdownName(cur)
}

func (n *node) SetDropdownInt(i int) {
	if ! n.ready() { return }
	n.tk.uiCombobox.SetSelected(i)
}

func (n *node) addDropdownName(s string) {
	if ! n.ready() { return }
	log.Log(INFO, "addDropdownName()", n.WidgetId, "add:", s)

	n.tk.uiCombobox.Append(s)
	if (n.tk.val == nil) {
		log.Log(INFO, "make map didn't work")
		return
	}
	n.tk.val[n.tk.c] = s

	// If this is the first menu added, set the dropdown to it
	if (n.tk.c == 0) {
		log.Log(INFO, "THIS IS THE FIRST Dropdown", s)
		n.tk.uiCombobox.SetSelected(0)
	}
	n.tk.c = n.tk.c + 1
}

func (n *node) setDropdownName(s string) bool {
	if ! n.ready() { return false}
	log.Log(INFO, "SetDropdownName()", n.WidgetId, ",", s)

	for i, tmp := range n.tk.val {
		if s == tmp {
			n.value = s
			n.SetDropdownInt(i)
			log.Warn("SetDropdownInt() worked", tmp, i)
			return true
		}
	}
	log.Warn("SetDropdownName() failed", s)
	return false
}
