package com.jsowell.common.enums.ykc;

import com.jsowell.common.util.StringUtils;
import io.netty.channel.Channel;
import lombok.extern.slf4j.Slf4j;

import java.util.HashMap;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 桩编号和channel的关联关系处理 entity
 */
@Slf4j
public class PileChannelEntity {

    /**
     * 管理一个全局map，保存连接进服务端的通道数量
     */
    private static final ConcurrentHashMap<String, Channel> manager = new ConcurrentHashMap<>();
 
    public static void put(String pileSn, Channel channel) {
        if (manager.containsKey(pileSn)) {
            log.error("桩编号:【{}】已经是连接状态", pileSn);
        }
        manager.put(pileSn, channel);
    }

    /**
     * 通过桩编号获取channel链接信息
     * @param pileSn
     * @return
     */
    public static Channel getChannelByPileSn(String pileSn) {
        return manager.get(pileSn);
    }

    /**
     * 通过channelId获取桩编号
     * @param channelId
     * @return
     */
    public static String getPileSnByChannelId(String channelId) {
        for (HashMap.Entry<String, Channel> entry : manager.entrySet()) {
           if (entry.getValue().id().asLongText().equals(channelId)) {
               return entry.getKey();
           }
        }
        return null;
    }

    /**
     * 打印
     */
    public static void output() {
        for (HashMap.Entry<String, Channel> entry : manager.entrySet()) {
            System.out.println("pileSn:" + entry.getKey() +
                    ",ChannelId:" + entry.getValue().id().asLongText());
        }
    }

    public static void removeByPileSn(String pileSn){
        if (StringUtils.isBlank(pileSn)) {
            return;
        }
        manager.remove(pileSn);
    }

    public static void removeByChannelId(String channelId){
        if (StringUtils.isBlank(channelId)) {
            return;
        }
        String pileSn = getPileSnByChannelId(channelId);
        if (StringUtils.isNotBlank(pileSn)) {
            manager.remove(pileSn);
        }
    }

}