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();
    }

    /**
     * 定时刷新（10分钟）
     */
    @Scheduled(fixedDelay = 10 * 60 * 1000)
    public void refresh() {
        try {
            List<MqttSensorDevice> list = deviceService.selectMqttSensorDeviceList(new MqttSensorDevice());

            Map<String, MqttSensorDevice> newCache = new ConcurrentHashMap<>();

            for (MqttSensorDevice device : list) {
                if (device.getDevEui() != null) {
                    newCache.put(device.getDevEui().toLowerCase(), device);
                }
            }

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

            log.info("[MQTT] 设备缓存刷新完成，数量={}", cache.size());

        } catch (Exception e) {
            log.error("[MQTT] 设备缓存刷新失败", e);
        }
    }

    /**
     * 获取设备
     */
    public MqttSensorDevice get(String devEui) {
        if (devEui == null) {
            return null;
        }
        return cache.get(devEui.toLowerCase());
    }
}