package com.shzg.project.worn.unit;

import com.shzg.project.worn.domain.MqttSensorDevice;
import com.shzg.project.worn.service.IMqttSensorDeviceService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Slf4j
@Component
public class MqttDeviceCache {

    @Autowired
    private IMqttSensorDeviceService deviceService;

    private final Map<String, MqttSensorDevice> cache = new ConcurrentHashMap<>();

    @PostConstruct
    public void init() {
        refresh();
    }

    @Scheduled(fixedDelay = 10 * 60 * 1000)
    public void refresh() {
        try {
            List<MqttSensorDevice> list = deviceService.selectAllForMqttCache();

            Map<String, MqttSensorDevice> newCache = new ConcurrentHashMap<>();
            int onlineCount = 0;
            int offlineCount = 0;

            for (MqttSensorDevice device : list) {
                if (device.getDevEui() != null) {
                    newCache.put(device.getDevEui().toLowerCase(), device);
                }
                if ("1".equals(device.getStatus())) {
                    offlineCount++;
                } else {
                    onlineCount++;
                }
            }

            cache.clear();
            cache.putAll(newCache);

            log.info("[MQTT] 设备缓存刷新完成, total={}, online={}, offline={}", cache.size(), onlineCount, offlineCount);
        } catch (Exception e) {
            log.error("[MQTT] 设备缓存刷新失败", e);
        }
    }

    public MqttSensorDevice get(String devEui) {
        if (devEui == null) {
            return null;
        }
        return cache.get(devEui.toLowerCase());
    }

    public void put(MqttSensorDevice device) {
        if (device == null || device.getDevEui() == null) {
            return;
        }
        cache.put(device.getDevEui().toLowerCase(), device);
    }
}
