package main

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

	"go.wit.com/log"
	"go.wit.com/toolkits/tree"
)

func newDropdown(p, n *tree.Node) {
	if notNew(n) {
		return
	}
	newt := new(guiWidget)
	log.Log(INFO, "gui.Toolbox.newDropdown() START", n.GetProgName())

	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.SetValue("map did not work. ui.Combobox error")
		} else {
			n.SetValue(newt.val[i])
		}
		me.myTree.DoUserEvent(n)
	})

	n.TK = newt
	place(p, n)

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

func setDropdownInt(n *tree.Node, i int) {
	if !ready(n) {
		return
	}
	var tk *guiWidget
	tk = n.TK.(*guiWidget)
	tk.uiCombobox.SetSelected(i)
}

func addDropdownName(n *tree.Node, s string) {
	if !ready(n) {
		return
	}
	var tk *guiWidget
	tk = n.TK.(*guiWidget)
	log.Log(INFO, "addDropdownName()", n.WidgetId, "add:", s)

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

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

func setDropdownName(n *tree.Node, s string) bool {
	if !ready(n) {
		return false
	}
	var tk *guiWidget
	tk = n.TK.(*guiWidget)
	log.Log(INFO, "SetDropdownName()", n.WidgetId, ",", s)

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