package main

import (
	"github.com/sirupsen/logrus"
	"net/http"
	_ "net/http/pprof"
	"os"
	"path/filepath"
	"runtime"

	"lc/common/models"
	"lc/common/util"
	"os/signal"
	"syscall"
)

var MySQLConfig util.MySQLConfig
var RedisConfig util.RedisConfig
var MQTTConfig util.MQTTConfig
var MqttconfigHl util.MQTTConfig //海蓝
var mainConfig MainConfig

var gopool *util.Pool
var IDGen util.IdWorker

func GetNextSeq() uint64 {
	u64, err := IDGen.NextId()
	if err != nil {
		logrus.Errorf("IDGen.NextId发生错误:%s", err.Error())
		u64 = util.MlNow().Unix()
	}
	return uint64(u64)
}

func InitMysql(conf *util.MySQLConfig) {
	models.InitDB(conf)
}
func DestroyMysql() {
	models.DestroyDB()
}

func ReadConfig() bool {
	dir, _ := os.Getwd() //filepath.Abs(filepath.Dir(os.Args[0]))
	fPath := dir + string(filepath.Separator) + "conf" + string(filepath.Separator)
	errA := RedisConfig.ReadConfig(fPath, "redis")
	errB := MySQLConfig.ReadConfig(fPath, "mysql")
	errC := MQTTConfig.ReadConfig(fPath, "broker")
	errD := mainConfig.ReadConfig(fPath, "ipolesvr")
	_ = MqttconfigHl.ReadConfig(fPath, "broker_highland")
	return errA && errB && errC && errD //&& err_e
}

func main() {

	signal.Ignore(syscall.SIGHUP)
	runtime.GOMAXPROCS(runtime.NumCPU())

	util.InitLogrus("release")

	err := IDGen.InitIdWorker(1000, 2)
	if err != nil {
		return
	}

	go func() {
		logrus.Infoln(http.ListenAndServe(":8197", nil))
	}()

	if !ReadConfig() {
		panic(nil)
	}
	GetMQTTMgr()
	GetHlMqttMgr() //hl
	InitMysql(&MySQLConfig)
	defer DestroyMysql()
	InitRedis(&RedisConfig)
	defer DestroyRedis()

	GetGwHandler().SubscribeTopics()
	GetModbusDeviceHandler().SubscribeTopics()
	GetChzbConcentratorMgr().SubscribeTopics()
	GetHlZigbeeConcentratorMgr().SubscribeTopics()
	GetSosMgr().SubscribeTopics()
	GetIPCMgr().SubscribeTopics()
	GetCltLedMgr().SubscribeTopics()
	GetYMLampControllerMgr().SubscribeTopics()
	GetItsMgr().SubscribeTopics()
	GetRadarHandler().SubscribeTopics()
	GetCableGuardianHandler().SubscribeTopics()

	calcTask()

	gopool = util.NewPool(20)
	gopool.Add(StatData, 1)
	gopool.Add(GetGwHandler().Handler, 2)               //网关
	gopool.Add(GetModbusDeviceHandler().Handler, 3)     //环境 水位
	gopool.Add(GetHlZigbeeConcentratorMgr().Handler, 4) //海蓝
	gopool.Add(GetChzbConcentratorMgr().Handler, 5)
	gopool.Add(GetLampStrategyMgr().Handler, 6)
	gopool.Add(GetSosMgr().Handler, 7)
	gopool.Add(GetIPCMgr().Handler, 8)
	gopool.Add(GetSrsMgr().Handler, 9)
	gopool.Add(GetEventMgr().Handler, 10)
	gopool.Add(GetCltLedMgr().Handler, 11)
	gopool.Add(GetYMLampControllerMgr().Handler, 12)
	gopool.Add(GetSrsMgr().StartWeb, 13)
	gopool.Add(GetItsMgr().Handler, 14)
	gopool.Add(GetBizAlarmMgr().Handler, 15)
	gopool.Add(GetRadarHandler().Handler, 16)
	gopool.Add(GetCableGuardianHandler().Handler, 17)
	gopool.Run()
	gopool.Wait()
}
