package tree

import (
	"go.wit.com/log"
	"go.wit.com/widget"
)

// this is in common.go, do not move it
func (me *TreeInfo) AddNode(a *widget.Action) *Node {
	n := new(Node)
	n.WidgetType = a.WidgetType
	n.WidgetId = a.WidgetId
	n.ParentId = a.ParentId

	n.State = a.State
	n.State.Enable = a.State.Enable
	// n.Strings = make(map[string]int)
	// slices.Reverse(lines)
	// dropdown strings
	n.ddStrings = make([]string, 0)
	for _, s := range a.State.Strings {
		n.ddStrings = append(n.ddStrings, s)
	}

	if a.WidgetType == widget.Root {
		log.Log(TREE, "AddNode() Root")
		n.Parent = n
		treeRoot = n
		return n
	}

	if treeRoot.FindWidgetId(a.WidgetId) != nil {
		log.Log(TREEWARN, "AddNode() WidgetId already exists", a.WidgetId)
		log.Log(TREEWARN, "probably this is a Show() / Hide() issue")
		log.Log(TREEWARN, "TODO: figure out what to do here")
		return treeRoot.FindWidgetId(a.WidgetId)
	}

	// add this new widget on the binary tree
	p := treeRoot.FindWidgetId(a.ParentId)
	n.Parent = p
	if n.Parent == nil {
		log.Log(TREEWARN, "AddNode() ERROR n.Parent == nil n =", n.WidgetId, n.WidgetType, n.GetProgName())
		log.Log(TREEWARN, "AddNode() ERROR n.Parent == nil a =", a.WidgetId, a.WidgetType, a.State.ProgName)
		log.Log(TREEWARN, "AddNode() ERROR n.Parent == nil a.pid =", a.ParentId)
		return n
	}
	log.Log(TREE, "AddNode() Adding to parent =", p.ParentId, p.WidgetType, p.GetProgName())
	log.Log(TREE, "AddNode() Adding     child =", n.ParentId, n.WidgetType, n.GetProgName())
	p.children = append(p.children, n)
	return n
}

func (n *Node) DeleteNode() {
	p := n.Parent
	for i, child := range p.children {
		log.Log(TREE, "parent has child:", i, child.WidgetId, child.GetProgName())
		if n == child {
			log.Log(TREE, "Found child ==", i, child.WidgetId, child.GetProgName())
			log.Log(TREE, "Found n ==", i, n.WidgetId, n.GetProgName())
			p.children = append(p.children[:i], p.children[i+1:]...)
		}
	}
	for i, child := range p.children {
		log.Log(TREE, "parent now has child:", i, child.WidgetId, child.GetProgName())
	}
}