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 newCombobox(p, n *tree.Node) {
	if notNew(n) {
		return
	}
	newt := new(guiWidget)

	cb := ui.NewEditableCombobox()
	newt.uiEditableCombobox = cb
	newt.uiControl = cb

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

	cb.OnChanged(func(spin *ui.EditableCombobox) {
		n.SetValue(spin.Text())
		log.Warn("combobox changed =" + spin.Text() + ".")
		me.myTree.DoUserEvent(n)
	})

	n.TK = newt
	place(p, n)

	log.Warn("add combobox entries on create:", n.State.Strings)
	log.Warn("add combobox entries on create:", n.State.Strings)
	log.Warn("add combobox entries on create:", n.State.Strings)
	// add the initial combobox entries
	for i, s := range n.State.Strings {
		log.Warn("add combobox entries on create", n.GetProgName(), i, s)
		addComboboxName(n, s)
	}
	cur := n.String()
	log.Warn("add combobox: TODO: set default value on create", n.GetProgName(), cur)
	setComboboxName(n, cur)
}

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

	tk.uiEditableCombobox.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 combobox", s)
		tk.uiEditableCombobox.SetText(s)
	}
	tk.c = tk.c + 1
}

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