package com.ruoyi.web.core.nfid;

import io.netty.channel.Channel;

import java.util.concurrent.ConcurrentHashMap;

public class DeviceSessionManager {
    private static final ConcurrentHashMap<String, String> channelToDeviceMap = new ConcurrentHashMap<>();
    private static final ConcurrentHashMap<String, Channel> deviceToChannelMap = new ConcurrentHashMap<>();

    /**
     * 检查Channel是否已注册设备
     * @param channel Netty Channel对象
     * @return 如果已注册返回true，否则返回false
     */
    public static boolean contains(Channel channel) {
        return channelToDeviceMap.containsKey(channel.id().asLongText());
    }

    // 注册设备连接
    public static void registerDevice(Channel channel, String deviceId) {
        String channelId = channel.id().asLongText();
        channelToDeviceMap.put(channelId, deviceId);
        deviceToChannelMap.put(deviceId, channel);
    }

    // 获取设备ID
    public static String getDeviceId(Channel channel) {
        return channelToDeviceMap.get(channel.id().asLongText());
    }

    // 获取设备Channel
    public static Channel getDeviceChannel(String deviceId) {
        return deviceToChannelMap.get(deviceId);
    }

    /**
     * 取消Channel的注册
     * @param channel Netty Channel对象
     */
    public static void unregister(Channel channel) {
        channelToDeviceMap.remove(channel.id().asLongText());
    }
}