package m9zApi

import (
	"encoding/json"
	"os"
	"path/filepath"
	"sync"

	g "tgk-touch/internal/global"

	"github.com/towgo/towgo/lib/system"
	"github.com/towgo/towgo/towgo"
)

type ScanConfigManager struct {
	mu        sync.RWMutex
	loopCount int
}

type ScanConfigData struct {
	LoopCount int `json:"loop_count"`
}

var scanConfigManager = &ScanConfigManager{}

func getScanConfigFilePath() string {
	return filepath.Join(system.GetPathOfProgram(), "data", "scanConfig.json")
}

func (m *ScanConfigManager) GetLoopCount() int {
	m.mu.RLock()
	defer m.mu.RUnlock()
	return normalizeLoopCount(m.loopCount)
}

func (m *ScanConfigManager) SetLoopCount(loopCount int) error {
	m.mu.Lock()
	defer m.mu.Unlock()

	m.loopCount = loopCount
	if err := m.saveToFile(); err != nil {
		return err
	}
	g.GVA_Config.DeviceInfo.LoopCount = loopCount
	return nil
}

func (m *ScanConfigManager) loadFromFile() error {
	m.mu.Lock()
	defer m.mu.Unlock()

	filePath := getScanConfigFilePath()
	jsonData, err := os.ReadFile(filePath)
	if err != nil {
		if os.IsNotExist(err) {
			m.loopCount = normalizeLoopCount(g.Config().DeviceInfo.LoopCount)
			return m.saveToFile()
		}
		return err
	}

	var data ScanConfigData
	if err := json.Unmarshal(jsonData, &data); err != nil {
		return err
	}
	m.loopCount = normalizeLoopCount(data.LoopCount)
	g.GVA_Config.DeviceInfo.LoopCount = m.loopCount
	return nil
}

func (m *ScanConfigManager) saveToFile() error {
	filePath := getScanConfigFilePath()
	dir := filepath.Dir(filePath)
	if err := os.MkdirAll(dir, 0755); err != nil {
		return err
	}

	jsonData, err := json.Marshal(ScanConfigData{
		LoopCount: normalizeLoopCount(m.loopCount),
	})
	if err != nil {
		return err
	}
	return os.WriteFile(filePath, jsonData, 0600)
}

func getScanConfig(rpcConn towgo.JsonRpcConnection) {
	rpcConn.WriteResult(map[string]interface{}{
		"loop_count":     scanConfigManager.GetLoopCount(),
		"max_loop_count": maxLoopCount,
		"min_loop_count": 1,
	})
}

type SetScanConfigReq struct {
	LoopCount int `json:"loop_count"`
}

func setScanConfig(rpcConn towgo.JsonRpcConnection) {
	var req SetScanConfigReq
	rpcConn.ReadParams(&req)

	if req.LoopCount < 1 || req.LoopCount > maxLoopCount {
		rpcConn.WriteError(400, "loop_count must be between 1 and 10")
		return
	}
	if err := scanConfigManager.SetLoopCount(req.LoopCount); err != nil {
		rpcConn.WriteError(500, "save scan config failed: "+err.Error())
		return
	}
	rpcConn.WriteResult(map[string]interface{}{
		"success":        true,
		"loop_count":     scanConfigManager.GetLoopCount(),
		"max_loop_count": maxLoopCount,
		"min_loop_count": 1,
	})
}
