package cfg

import (
	"cicv-data-closedloop/pji/common/cutil"
	"cicv-data-closedloop/pji/common/log"
	"gopkg.in/yaml.v3"
	"os"
	"sync"
	"time"
)

type Platform struct {
	UrlDeviceAuth string `yaml:"url-device-auth"`
	UrlTaskPoll   string `yaml:"url-task-poll"`
	UrlTask       string `yaml:"url-task"`
}

type Host struct {
	Name   string   `yaml:"name"`
	Ip     string   `yaml:"ip"`
	Topics []string `yaml:"topics"`
}
type Ros struct {
	MasterAddress string   `yaml:"master-address"`
	Nodes         []string `yaml:"nodes"`
}

type cloudConfig struct {
	FullCollect           bool      `yaml:"full-collect"`
	ConfigRefreshInterval int       `yaml:"config-refresh-interval"` // 配置刷新时间间隔
	BagNumber             int       `yaml:"bag-number"`
	TimeWindowSendGap     int       `yaml:"time-window-send-gap"` // 主节点向从节点发送窗口的最小时间间隔
	DiskUsage             float64   `yaml:"disk-usage"`
	BagDataDir            string    `yaml:"bag-data-dir"`
	BagCopyDir            string    `yaml:"bag-copy-dir"`
	TriggersDir           string    `yaml:"triggers-dir"`
	TcpPort               string    `yaml:"tcp-port"`
	RpcPort               string    `yaml:"rpc-port"`
	Triggers              []Trigger `yaml:"triggers"`
	Hosts                 []Host    `yaml:"hosts"`
	Ros                   Ros       `yaml:"ros"`
	Platform              Platform  `yaml:"platform"`
}

type Trigger struct {
	Label  string   `yaml:"label"`
	Topics []string `yaml:"topics"`
}

var (
	CloudConfig      cloudConfig
	CloudConfigMutex sync.RWMutex
)

// InitCloudConfig 初始化业务配置
func InitCloudConfig() {
	log.GlobalLogger.Info("初始化OSS配置文件 - 开始。")
	// 获取文件的目录
	cutil.CreateParentDir(LocalConfig.CloudConfigLocalPath)
	// 3 ------- 获取 yaml 字符串 -------
	var content []byte
	cloudConfigObjectKey := LocalConfig.OssBasePrefix + LocalConfig.EquipmentNo + "/" + LocalConfig.CloudConfigFilename
	err := OssBucket.GetObjectToFile(cloudConfigObjectKey, LocalConfig.CloudConfigLocalPath)
	if err != nil {
		log.GlobalLogger.Error("程序崩溃,下载oss上的配置文件"+cloudConfigObjectKey+"失败。", err)
		os.Exit(-1)
	}

	content, err = os.ReadFile(LocalConfig.CloudConfigLocalPath)
	if err != nil {
		log.GlobalLogger.Error("程序崩溃,配置文件 ", LocalConfig.CloudConfigLocalPath, " 读取失败:", err)
		os.Exit(-1)
	}

	// 4 ------- 解析YAML内容 -------
	var newCloudConfig cloudConfig
	err = yaml.Unmarshal(content, &newCloudConfig)
	if err != nil {
		log.GlobalLogger.Error("程序崩溃,配置文件 ", LocalConfig.CloudConfigLocalPath, " 解析失败:", err)
		os.Exit(-1)
	}

	// 5 ------- 校验 yaml -------
	if checkConfig(newCloudConfig) {
		CloudConfigMutex.RLock()
		CloudConfig = newCloudConfig
		CloudConfigMutex.RUnlock()
	} else {
		log.GlobalLogger.Error("程序崩溃,配置文件格式错误:", newCloudConfig)
		os.Exit(-1)
	}
	log.GlobalLogger.Info("初始化OSS配置文件 - 成功。")
	cutil.CreateDir(CloudConfig.BagDataDir)
	cutil.CreateDir(CloudConfig.BagCopyDir)
}

// refreshCloudConfig 更新业务配置
func refreshCloudConfig() {
	// 获取文件的目录
	cutil.CreateParentDir(LocalConfig.CloudConfigLocalPath)
	// 3 ------- 获取 yaml 字符串 -------
	var content []byte
	cloudConfigObjectKey := LocalConfig.OssBasePrefix + LocalConfig.EquipmentNo + "/" + LocalConfig.CloudConfigFilename
	err := OssBucket.GetObjectToFile(cloudConfigObjectKey, LocalConfig.CloudConfigLocalPath)
	if err != nil {
		log.GlobalLogger.Error("下载oss上的配置文件"+cloudConfigObjectKey+"失败。", err)
		//os.Exit(-1)
	}

	content, err = os.ReadFile(LocalConfig.CloudConfigLocalPath)
	if err != nil {
		log.GlobalLogger.Error("配置文件 ", LocalConfig.CloudConfigLocalPath, " 读取失败:", err)
		os.Exit(-1)
	}

	// 4 ------- 解析YAML内容 -------
	var newCloudConfig cloudConfig
	err = yaml.Unmarshal(content, &newCloudConfig)
	if err != nil {
		log.GlobalLogger.Error("配置文件 ", LocalConfig.CloudConfigLocalPath, " 解析失败:", err)
		os.Exit(-1)
	}

	// 5 ------- 校验 yaml -------
	if checkConfig(newCloudConfig) {
		CloudConfigMutex.RLock()
		CloudConfig = newCloudConfig
		CloudConfigMutex.RUnlock()
	} else {
		log.GlobalLogger.Error("配置文件格式错误:", newCloudConfig)
		os.Exit(-1)
	}
	cutil.CreateDir(CloudConfig.BagDataDir)
	cutil.CreateDir(CloudConfig.BagCopyDir)
}

// RefreshCloudConfig 轮询oss上的配置文件更新到本地
func RefreshCloudConfig() {
	for {
		time.Sleep(time.Duration(CloudConfig.ConfigRefreshInterval) * time.Second)
		refreshCloudConfig()
	}
}

// CheckConfig 校验 cfg.yaml 文件
func checkConfig(check cloudConfig) bool {
	if len(check.Hosts) != 1 {
		log.GlobalLogger.Error("cloud-config.yaml中配置的hosts必须为1。")
		os.Exit(-1)
	}
	return true

}