package main

import (
	"errors"
	"strings"

	"github.com/go-ini/ini"
)

var CheckOfflineInterval = 1
var OfflineInterval float64 = 5

func GetVagueTopic(devtype, topic string) string {
	return "+/" + devtype + "/+/" + topic
}

func GetCltledTopic(topic string) string {
	return "+/cltled/+/up/" + topic + "/+"
}

func GetTopic(tenant, devtype, id, topic string) string {
	return tenant + "/" + devtype + "/" + id + "/" + topic
}
func GetHLTopicDown(tenant, devType, id, topic string) string {
	return "hllk/113/lamp/longchi/down"
}
func GetHLTopicUp() string {
	return "hllk/113/lamp/longchi/up"
}

// ParseTopic 获取租户、设备类型、设备编码、MQTT协议topic固定部分（定义在topic.go文件）
func ParseTopic(topic string) (string, string, string, string, error) {
	strList := strings.Split(topic, "/")
	if len(strList) < 4 {
		return "", "", "", "", errors.New("不支持的topic")
	}
	topic = strings.Join(strList[3:], "/")
	return strList[0], strList[1], strList[2], topic, nil
}

// ParseTopicHL 获取租户、设备类型、设备编码、MQTT协议topic固定部分（定义在topic.go文件）
func ParseTopicHL(topic string) (string, string, error) {
	strList := strings.Split(topic, "/")
	if len(strList) < 4 {
		return "", "", errors.New("不支持的topic")
	}
	if strList[3] == "longchi" {
		strList[0] = "100000"
	}
	return strList[0], topic, nil
}

// ParseTopicHL 获取租户、设备类型、设备编码、MQTT协议topic固定部分, request（定义在topic.go文件）
func ParseTopicCltLed(topic string) (string, string, string, string, string, error) {
	strList := strings.Split(topic, "/")
	if len(strList) < 6 {
		return "", "", "", "", "", errors.New("不支持的topic")
	}
	//+/cltled/+/up/query/+
	return strList[0], strList[1], strList[2], strList[4], strList[5], nil
}

type MainConfig struct {
	GB28181API    string
	SRSLIVEDIR    string
	SRSLIVEMP4    int
	SDKAppId      string
	SecretId      string
	SecretKey     string
	SMSKey        string
	SMSTemplateId string
	SMSReceiver   []string
}

func (o *MainConfig) ReadConfig(path, sec string) bool {
	var ret = false
	fini, err := ini.Load(path + "main.ini")
	if err == nil {
		fsec := fini.Section(sec)
		if fsec != nil {
			err := fsec.StrictMapTo(&o)
			if err != nil {
				panic(path + " ReadConfig MainConfig err = " + err.Error())
				return false
			}
			//o.GB28181API = fsec.Key("GB28181API").String()
			//o.SRSLIVEDIR = fsec.Key("SRSLIVEDIR").String()
			//o.SRSLIVEMP4, _ = fsec.Key("SRSLIVEMP4").Int()
			//o.SDKAppId = fsec.Key("SDKAppId").String()
			//o.SecretId = fsec.Key("SecretId").String()
			//o.SecretKey = fsec.Key("SecretKey").String()
			//o.SMSTemplateId = fsec.Key("SMSTemplateId").String()
			//o.SMSKey = fsec.Key("SMSKey").String()
			//o.SMSReceiver = fsec.Key("SMSReceiver").
			if o.SRSLIVEMP4 <= 0 || o.SRSLIVEMP4 > 8640 {
				o.SRSLIVEMP4 = 48
			}
			ret = true
		}
	}
	return ret
}
