package main

import (
	"fmt"
	"os"
	"time"

	"git.wecise.com/wecise/odb-go/odbc"
	"git.wecise.com/wecise/odbtools/omtool"
	"gitee.com/wecisecode/util/cmap"
)

var mcfg, logger = odbc.SetDefaultAppName("odbtools")

func main() {
	odbtools := NewODBTools()
	e := odbtools.Init()
	if e != nil {
		println(fmt.Sprint(e))
		os.Exit(1)
		return
	}
	e = odbtools.Run()
	if e != nil {
		println(fmt.Sprint(e))
		os.Exit(1)
		return
	}
	time.Sleep(1 * time.Second)
}

type ODBTools struct {
	tools cmap.ConcurrentMap[omtool.OMTool, bool]
}

func NewODBTools() *ODBTools {
	tools := cmap.NewSingle(map[omtool.OMTool]bool{
		// datasync.NewDataSync(): false,
	})
	return &ODBTools{
		tools: tools,
	}
}

func (ots *ODBTools) Init() error {
	for i := range ots.tools.IterBuffered() {
		e := i.Key.Init()
		if e != nil {
			if !odbc.NoConfError.Contains(e) {
				return e
			}
			ots.tools.Set(i.Key, false)
		} else {
			ots.tools.Set(i.Key, true)
			logger.Info(fmt.Sprintf("%T inited", i.Key))
		}
	}
	return nil
}

func (ots *ODBTools) Run() error {
	dones := map[omtool.OMTool]<-chan error{}
	for i := range ots.tools.IterBuffered() {
		configured := i.Val
		if configured {
			done := i.Key.Run()
			if done != nil {
				dones[i.Key] = done
			} else {
				logger.Info(fmt.Sprintf("%T not run", i.Key))
			}
		}
	}
	for len(dones) > 0 {
		for kt, done := range dones {
			select {
			case e := <-done:
				logger.Info(fmt.Sprintf("%T done", kt))
				if e != nil {
					logger.Error(e)
				}
				delete(dones, kt)
			default:
			}
		}
		time.Sleep(1 * time.Second)
	}
	return nil
}
