package main

import (
	"fmt"

	"gopkg.in/ini.v1"
)

type MQTTBroker struct {
	Address  string `ini:"BrokerAddress"` // 地址端口
	Username string `ini:"Username"`      // 用户名称
	Password string `ini:"Password"`      // 接入密码
}

type CmdTimeout struct {
	Prefix  string `ini:"Prefix"`  ///////// 命令前缀
	Timeout int    `ini:"Timeout"` /// 超时, 单位: 秒
}

type Config struct {
	MQTTSrv MQTTBroker            `ini:"MQTTSrv"`
	Cmds    map[string]CmdTimeout /// key = ini的节名
}

var (
	CfgServers = &Config{}
)

func loadAppConfig() error {
	cfgFile := "./config.ini"
	cfgIni, err := ini.Load(cfgFile)
	if err != nil {
		return err
	}

	if cfgIni.HasSection("MQTTSrv") {
		if err := cfgIni.Section("MQTTSrv").MapTo(&CfgServers.MQTTSrv); err != nil {
			return err
		}
	} else {
		return fmt.Errorf("配置文件\"%s\"缺少\"[MQTTSrv]\"节", cfgFile)
	}

	CfgServers.Cmds = make(map[string]CmdTimeout)

	for _, sec := range cfgIni.Sections() {
		secName := sec.Name()

		if secName == ini.DefaultSection || secName == "MQTTSrv" {
			continue
		}

		var cmd CmdTimeout
		if err := sec.MapTo(&cmd); err != nil || cmd.Prefix == "" || cmd.Timeout <= 0 {
			continue
		}

		CfgServers.Cmds[secName] = cmd
	}

	return nil
}

func getCmdTimeoutByPrefix(cmd string) int {
	if cmd == "" || len(CfgServers.Cmds) == 0 {
		return -1
	}

	for _, c := range CfgServers.Cmds {
		if c.Prefix != "" && len(cmd) >= len(c.Prefix) &&
			cmd[:len(c.Prefix)] == c.Prefix {
			return c.Timeout
		}
	}

	return -1
}
