// Package service 提供各种业务服务功能
package service

import (
	"sync"
)

// DeviceStatus 设备状态信息
type DeviceStatus struct {
	// Active 设备是否启动
	Active bool
}

// DeviceStatusPool 设备状态池，用于管理所有设备的当前状态
type DeviceStatusPool struct {
	// statuses 设备状态映射 设备ID:状态
	statuses map[string]*DeviceStatus

	// mutex 读写锁，保证并发安全
	mutex sync.RWMutex
}

// NewDeviceStatusPool 创建设备状态池实例
func NewDeviceStatusPool() *DeviceStatusPool {
	return &DeviceStatusPool{
		statuses: make(map[string]*DeviceStatus),
	}
}

// SetStatus 设置设备状态
func (dsp *DeviceStatusPool) SetStatus(deviceID string, status *DeviceStatus) {
	dsp.mutex.Lock()
	defer dsp.mutex.Unlock()

	dsp.statuses[deviceID] = status
}

// GetStatus 获取设备状态
func (dsp *DeviceStatusPool) GetStatus(deviceID string) (*DeviceStatus, bool) {
	dsp.mutex.RLock()
	defer dsp.mutex.RUnlock()

	status, exists := dsp.statuses[deviceID]
	return status, exists
}

// DeleteStatus 删除设备状态
func (dsp *DeviceStatusPool) DeleteStatus(deviceID string) {
	dsp.mutex.Lock()
	defer dsp.mutex.Unlock()

	delete(dsp.statuses, deviceID)
}

// GetAllStatuses 获取所有设备状态
func (dsp *DeviceStatusPool) GetAllStatuses() map[string]*DeviceStatus {
	dsp.mutex.RLock()
	defer dsp.mutex.RUnlock()

	// 创建副本以避免外部修改
	result := make(map[string]*DeviceStatus)
	for id, status := range dsp.statuses {
		result[id] = status
	}

	return result
}

// SetAllStatuses 全量更新设备状态池
func (dsp *DeviceStatusPool) SetAllStatuses(statuses map[string]*DeviceStatus) {
	dsp.mutex.Lock()
	defer dsp.mutex.Unlock()

	// 清空现有状态
	for id := range dsp.statuses {
		delete(dsp.statuses, id)
	}

	// 添加新状态
	for id, status := range statuses {
		dsp.statuses[id] = status
	}
}
