package main

import (
	// if you include more than just this import
	// then your plugin might be doing something un-ideal (just a guess from 2023/02/27)
	"go.wit.com/lib/widget"
	"go.wit.com/log"
)

func action(a *widget.Action) {
	log.Log(INFO, "action() START", a.WidgetId, a.ActionType, a.WidgetType, a.ProgName)
	n := me.rootNode.findWidgetId(a.WidgetId)
	var w *guiWidget
	if n != nil {
		w = n.tk
	}
	switch a.ActionType {
	case widget.Add:
		if w == nil {
			n := addNode(a)
			// w = n.tk
			n.addWidget()
		} else {
			// this is done to protect the plugin being 'refreshed' with the
			// widget binary tree. TODO: find a way to keep them in sync
			log.Log(ERROR, "action() Add ignored for already defined widget",
				a.WidgetId, a.ActionType, a.WidgetType, a.ProgName)
		}
	case widget.Show:
		if widget.GetBool(a.Value) {
			n.showView()
		} else {
			n.hideWidgets()
		}
	case widget.Set:
		if a.WidgetType == widget.Flag {
			log.Log(NOW, "TODO: set flag here", a.ActionType, a.WidgetType, a.ProgName)
			log.Log(NOW, "TODO: n.WidgetType =", n.WidgetType, "n.progname =", a.ProgName)
		} else {
			if a.Value == nil {
				log.Log(ERROR, "TODO: Set here. a == nil id =", a.WidgetId, "type =", a.WidgetType, "Name =", a.ProgName)
				log.Log(ERROR, "TODO: Set here. id =", a.WidgetId, "n.progname =", n.progname)
			} else {
				n.Set(a.Value)
			}
		}
	case widget.SetText:
		n.SetText(widget.GetString(a.Value))
	case widget.AddText:
		n.AddText(widget.GetString(a.Value))
	case widget.Move:
		log.Log(NOW, "attempt to move() =", a.ActionType, a.WidgetType, a.ProgName)
	case widget.ToolkitClose:
		log.Log(NOW, "attempting to close the plugin and release stdout and stderr")
		standardExit()
	case widget.Enable:
		if n.Visible() {
			// widget was already shown
		} else {
			log.Log(INFO, "Setting Visable to true", a.ProgName)
			n.SetVisible(true)
		}
	case widget.Disable:
		if n.Visible() {
			log.Log(INFO, "Setting Visable to false", a.ProgName)
			n.SetVisible(false)
		} else {
			// widget was already hidden
		}
	default:
		log.Log(ERROR, "action() ActionType =", a.ActionType, "WidgetType =", a.WidgetType, "Name =", a.ProgName)
	}
	log.Log(INFO, "action() END")
}

func (n *node) AddText(text string) {
	if n == nil {
		log.Log(NOW, "widget is nil")
		return
	}
	n.vals = append(n.vals, text)
	for i, s := range n.vals {
		log.Log(NOW, "AddText()", n.progname, i, s)
	}
	n.SetText(text)
}

func (n *node) SetText(text string) {
	var changed bool = false
	if n == nil {
		log.Log(NOW, "widget is nil")
		return
	}
	if widget.GetString(n.value) != text {
		n.value = text
		changed = true
	}
	if !changed {
		return
	}

	if n.Visible() {
		n.textResize()
		n.deleteView()
		n.showView()
	}
}

func (n *node) Set(val any) {
	// w := n.tk
	log.Log(INFO, "Set() value =", val)

	n.value = val
	if n.WidgetType != widget.Checkbox {
		n.setCheckbox(val)
	}
}
