package mcu_ctrl_board

import (
	"fmt"
	"os"
	"path/filepath"
	"sync"

	"gopkg.in/ini.v1"
	"hnyfkj.com.cn/rtu/bxs-sy/baseapp"
)

type Config struct {
	Version           string `ini:"Version"`                  // 版本号
	CtrlMode          int    `ini:"CtrlMode"`                 // 定时控制模式(0=光控, 1=时控)
	LightDuration     int    `ini:"LightDuration"`            // 光控定时时长(小时, 1-10, 仅光控模式有效)
	StartHour         int    `ini:"StartHour"`                // 时控开始时间(小时, 0-23, 仅时控模式有效)
	EndHour           int    `ini:"EndHour"`                  // 时控结束时间(小时, 0-23, 仅时控模式有效)
	TakePhotoInterval int    `ini:"TakePhotoIntervalMinutes"` // 拍照间隔(分钟)
}

var (
	CfgParams = &Config{
		Version:           "0.0.0.1",
		CtrlMode:          1,
		LightDuration:     10,
		StartHour:         0,
		EndHour:           23,
		TakePhotoInterval: 60,
	}
	mu sync.Mutex
)

func loadCfgParams() error {
	mu.Lock()
	defer mu.Unlock()

	cfgFile := filepath.Join(baseapp.CFG_DIR, "mcuparams.ini")
	cfgIni, err := ini.Load(cfgFile)
	if err != nil {
		return err
	}

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

	var verCode baseapp.VersionCode
	err = verCode.FromString(CfgParams.Version)
	if err != nil {
		return fmt.Errorf("配置文件\"%s\"的\"MCUSchedule.Version\"值\"%s\"无效", cfgFile, CfgParams.Version)
	}

	mcuCtrlBoard_ConfParameters(uint32(verCode), uint8(CfgParams.CtrlMode), uint8(CfgParams.LightDuration), uint8(CfgParams.StartHour), uint8(CfgParams.EndHour), uint16(CfgParams.TakePhotoInterval))

	return nil
}

func SaveCfgParams(setParams *Config) error {
	mu.Lock()
	defer mu.Unlock()

	cfgFile := filepath.Join(baseapp.CFG_DIR, "mcuparams.ini")
	cfgIni, err := ini.Load(cfgFile)
	if err != nil {
		cfgIni = ini.Empty()
	}

	sec, err := cfgIni.GetSection("MCUSchedule")
	if err != nil {
		sec, _ = cfgIni.NewSection("MCUSchedule")
	}

	sec.Key("Version").SetValue(setParams.Version)
	sec.Key("CtrlMode").SetValue(fmt.Sprintf("%d", setParams.CtrlMode))
	sec.Key("LightDuration").SetValue(fmt.Sprintf("%d", setParams.LightDuration))
	sec.Key("StartHour").SetValue(fmt.Sprintf("%d", setParams.StartHour))
	sec.Key("EndHour").SetValue(fmt.Sprintf("%d", setParams.EndHour))
	sec.Key("TakePhotoIntervalMinutes").SetValue(fmt.Sprintf("%d", setParams.TakePhotoInterval))

	tmpFile := cfgFile + ".tmp"
	if err := cfgIni.SaveToIndent(tmpFile, " "); err != nil {
		return fmt.Errorf("write temp ini failed: %w", err)
	}

	if err := os.Rename(tmpFile, cfgFile); err != nil {
		os.Remove(tmpFile)
		return fmt.Errorf("replace ini failed: %w", err)
	}

	return nil
}
