// Although most code from WIT.COM Inc is under the GPL
// This code is more generic because it must be able
// to be used in any GUI plugin

package tree

import (
	"fmt"
	"os"
	"runtime/debug"
	"sync"

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

var muAction sync.Mutex

func (me *TreeInfo) catchActionChannel() {
	defer func() {
		if r := recover(); r != nil {
			log.Log(TREEWARN, "YAHOOOO. Recovered in tree.catchActionChannel()", r)
			log.Log(TREEWARN, "YAHOOOO. Recovered in tree.catchActionChannel() Plugin:", me.PluginName)
			me.SendToolkitPanic()
			debug.PrintStack()
			me.ToolkitClose()
			if me.PluginName == "nocui" {
				os.Exit(-1)
			}
		}
	}()
	log.Log(TREE, "catchActionChannel() START")
	for {
		log.Log(TREE, "catchActionChannel() for loop")
		select {
		case a := <-me.pluginChan:
			log.Verbose("catchActionChannel() on ", a.WidgetId, a.WidgetType, a.ProgName)
			muAction.Lock()
			me.WaitOK()
			// time.Sleep(10 * time.Millisecond)
			me.doAction(a)
			muAction.Unlock()
		}
	}
}

func New() *TreeInfo {
	me := new(TreeInfo)
	me.pluginChan = make(chan widget.Action, 1)
	me.config = configLoad()

	log.Log(TREE, "Init() start channel reciever")
	go me.catchActionChannel()
	log.Log(TREE, "Init() END")
	return me
}

func (t *TreeInfo) ConfigFind(n string) (string, error) {
	all := t.config.All() // get the list of repos
	for all.Scan() {
		r := all.Next()
		if t.PluginName != r.Plugin {
			continue
		}
		if n == r.Name {
			return r.Value, nil
		}
		log.Info("toolkit config", r.Plugin, r.Name, r.Value, n)
	}
	return "", fmt.Errorf("toolkit config %s not found", n)
}