package device

import (
	"sync"
)

// Device 设备信息
type Device struct {
	ID        string `json:"id"`
	Name      string `json:"name"`
	IP        string `json:"ip"`
	Token     string `json:"token"`  // 设备认证令牌
	Status    string `json:"status"` // active, inactive, offline
	CreatedAt int64  `json:"created_at"`
	UpdatedAt int64  `json:"updated_at"`
}

// Storage 设备存储接口
type Storage interface {
	// GetDevices 获取所有设备
	GetDevices() []Device
	// GetDevice 获取指定设备
	GetDevice(id string) (Device, bool)
	// GetDeviceByToken 通过令牌获取设备
	GetDeviceByToken(token string) (Device, bool)
	// AddDevice 添加设备
	AddDevice(device Device) error
	// UpdateDevice 更新设备
	UpdateDevice(device Device) error
	// DeleteDevice 删除设备
	DeleteDevice(id string) error
	// UpdateDeviceStatus 更新设备状态
	UpdateDeviceStatus(id string, status string) error
}

// MemoryStorage 内存设备存储
type MemoryStorage struct {
	devices map[string]Device
	mutex   sync.RWMutex
}

// NewMemoryStorage 创建内存设备存储实例
func NewMemoryStorage() *MemoryStorage {
	return &MemoryStorage{
		devices: make(map[string]Device),
	}
}

// GetDevices 获取所有设备
func (s *MemoryStorage) GetDevices() []Device {
	s.mutex.RLock()
	defer s.mutex.RUnlock()

	devices := make([]Device, 0, len(s.devices))
	for _, device := range s.devices {
		devices = append(devices, device)
	}

	return devices
}

// GetDevice 获取指定设备
func (s *MemoryStorage) GetDevice(id string) (Device, bool) {
	s.mutex.RLock()
	defer s.mutex.RUnlock()

	device, ok := s.devices[id]
	return device, ok
}

// AddDevice 添加设备
func (s *MemoryStorage) AddDevice(device Device) error {
	s.mutex.Lock()
	defer s.mutex.Unlock()

	// 检查设备是否已存在
	if _, ok := s.devices[device.ID]; ok {
		return nil // 设备已存在，不重复添加
	}

	s.devices[device.ID] = device
	return nil
}

// UpdateDevice 更新设备
func (s *MemoryStorage) UpdateDevice(device Device) error {
	s.mutex.Lock()
	defer s.mutex.Unlock()

	// 检查设备是否存在
	if _, ok := s.devices[device.ID]; !ok {
		return nil // 设备不存在，不更新
	}

	s.devices[device.ID] = device
	return nil
}

// DeleteDevice 删除设备
func (s *MemoryStorage) DeleteDevice(id string) error {
	s.mutex.Lock()
	defer s.mutex.Unlock()

	delete(s.devices, id)
	return nil
}

// GetDeviceByToken 通过令牌获取设备
func (s *MemoryStorage) GetDeviceByToken(token string) (Device, bool) {
	s.mutex.RLock()
	defer s.mutex.RUnlock()

	for _, device := range s.devices {
		if device.Token == token {
			return device, true
		}
	}

	return Device{}, false
}

// UpdateDeviceStatus 更新设备状态
func (s *MemoryStorage) UpdateDeviceStatus(id string, status string) error {
	s.mutex.Lock()
	defer s.mutex.Unlock()

	device, ok := s.devices[id]
	if !ok {
		return nil // 设备不存在，不更新
	}

	device.Status = status
	s.devices[id] = device
	return nil
}
