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<>();
 
    /**
     * 校验channel是否保存
     */
    public static void checkChannel(String pileSn, Channel channel) {
        if (!manager.containsKey(pileSn)) {
            // 如果manager中不存在pileSn的连接，则保存
            log.info("checkChannel-manager中不存在pileSn:{}的连接,保存新的channel:{}", pileSn, channel.id().asLongText());
            manager.put(pileSn, channel);
            return;
        }

        // 如果manager中存在pileSn的连接，取出来对比
        Channel sourceChannel = manager.get(pileSn);
        if (sourceChannel == null) {
            // 为空就put
            log.info("checkChannel-manager中pileSn:{}的连接为空,保存新的channel:{}", pileSn, channel.id().asLongText());
            manager.put(pileSn, channel);
            return;
        }

        // 两个做对比
        String sourceChannelId = sourceChannel.id().asLongText();
        String channelId = channel.id().asLongText();
        if (!StringUtils.equals(sourceChannelId, channelId)) {
            // 不一致则更新
            log.info("checkChannel-manager中pileSn:{}的连接不一致, 老channelId:{}, 保存新的channel:{}", pileSn, sourceChannelId, channelId);
            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);
        }
    }

}