package com.zksy.pole.MQTTServer.channel;

import com.zksy.pole.MQTTServer.server.MQTTServer;
import io.netty.channel.Channel;
import io.netty.channel.ChannelId;
import lombok.extern.slf4j.Slf4j;

import java.util.List;
import java.util.Map;

/**
 * @author ShaoYang
 * @date 2024/03/13 16:53
 */
@Slf4j
public class MQTTDeviceManerger {
    /**
     * 设备接入
     */
    public static void MQTTdeviceAdd(Channel channel) {
        if(!MQTTServer.MQTTdeviceChannelGroup.contains(channel)) {
            MQTTServer.MQTTdeviceChannelGroup.add(channel);
        }
    }
    /**
     * 设备移除和和订阅的topic
     */
    public static void MQTTdeviceRemove(Channel channel) {
        if(MQTTServer.MQTTdeviceChannelGroup.contains(channel)) {
            MQTTServer.MQTTdeviceChannelGroup.remove(channel);
            MQTTremoveDeviceChannelId(channel.id());
            //移除topic中的这个设备的chanelid
            for (Map.Entry<String, List<ChannelId>> listEntry : MQTTServer.subscribeMap.entrySet()) {
                try {
                    if (listEntry.getValue().contains(channel.id())) {
                        listEntry.getValue().remove(channel.id());
                        log.info(channel.id() + "下线,topic:  " + listEntry.getKey() + "中移除此id");
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }
    public static void MQTTremoveDeviceChannelId(ChannelId channelId) {
        MQTTServer.MQTTdeviceMap.entrySet().removeIf(item -> item.getValue().equals(channelId));
    }
}
