// Author: NiuJiuRu
// Email: niujiuru@qq.com
// Date: 2025-11-20

package mcu_ctrl_board

import (
	"encoding/json"
	"fmt"
	"sync"

	"hnyfkj.com.cn/rtu/linux/utils/jsonrpc2"
)

type Config struct {
	SensorDataInterval string   `json:"sensor_data_interval"`
	PhotoTimes         []string `json:"photo_times"`
}

var (
	CfgParams = &Config{
		SensorDataInterval: "",         // 默认空
		PhotoTimes:         []string{}, // 默认空
	}
	mu sync.Mutex
)

const reqTimeout = 1000 // 请求超时, 单位: ms

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

	req, err := jsonrpc2.BuildRequest("get_mcu_params", nil, 1)
	if err != nil {
		return err
	}

	resp, err := Board.sendRequest(req, reqTimeout)
	if err != nil {
		return err
	}

	if resp.Error != nil {
		return fmt.Errorf("MCU返回错误: %d, %s", resp.Error.Code, resp.Error.Message)
	}

	var params Config
	if err := json.Unmarshal(resp.Result, &params); err != nil {
		return err
	}

	CfgParams = &params

	return nil
}

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

	req, err := jsonrpc2.BuildRequest("set_mcu_params", setParams, 2)
	if err != nil {
		return err
	}

	resp, err := Board.sendRequest(req, reqTimeout)
	if err != nil {
		return err
	}

	if resp.Error != nil {
		return fmt.Errorf("MCU返回错误: %d, %s", resp.Error.Code, resp.Error.Message)
	}

	CfgParams = setParams

	return nil
}
