package com.zg.framework.websocket.config;

import com.zg.project.Inventory.AutoInventory.service.IRfidService;
import com.zg.project.Inventory.AutoInventory.utils.SpringContextUtils;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.websocket.Session;
import java.io.IOException;
import java.util.Iterator;
import java.util.Map;

@Component
public class DeviceSessionCleaner {

    private static final long TIMEOUT = 30 * 1000; // 30秒无响应视为失联

    @Scheduled(fixedDelay = 10000) // 每10秒检查一次
    public void checkTimeoutSessions() {
        Iterator<Map.Entry<String, DeviceSession>> iterator = WebSocketServer.deviceSessionMap.entrySet().iterator();

        IRfidService rfidService = SpringContextUtils.getBean(IRfidService.class);

        while (iterator.hasNext()) {
            Map.Entry<String, DeviceSession> entry = iterator.next();
            String deviceId = entry.getKey();
            DeviceSession deviceSession = entry.getValue();
            long lastActive = deviceSession.getLastActiveTime();

            if (System.currentTimeMillis() - lastActive > TIMEOUT) {
                try {
                    Session session = deviceSession.getSession();
                    if (session != null && session.isOpen()) {
                        session.close(); // 主动断开连接
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }

                rfidService.disconnect(deviceId); // 释放设备连接
                iterator.remove(); // 移除超时设备
                WebSocketServer.sessionMap.remove(deviceId); // 保持一致性

                System.out.println("🛑 超时释放设备连接 deviceId=" + deviceId);
            }
        }
    }
}
