package org.jeecg.modules.nettyServer.store;

import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelId;
import io.netty.channel.ChannelOutboundInvoker;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.util.AttributeKey;
import io.netty.util.concurrent.GlobalEventExecutor;
import io.netty.util.internal.StringUtil;
import lombok.extern.slf4j.Slf4j;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 频道信息存储
 * <p>
 * 封装netty的频道存储，客户端id和频道双向绑定
 *
 * @author cn2008tv
 */
@Slf4j
public class WellChannelStore {

    /**
     * 频道绑定 key
     */
    private final static AttributeKey<Object> CLIENT_ID = AttributeKey.valueOf("clientId");

    /**
     * 井号绑定 key
     */
    private final static AttributeKey<Object> WELL_ID = AttributeKey.valueOf("wellId");

    /**
     * 是否推送井数据
     */
    private final static AttributeKey<Boolean> IS_PULL = AttributeKey.valueOf("isPull");

    /**
     * 是否推送预警信息
     */
    private final static AttributeKey<Boolean> IS_WARNING_PULL = AttributeKey.valueOf("isWarningPull");


    /**
     * 井号与客户端和频道绑定（一个井号可能有多个客户端关注）
     */
    private final static ConcurrentHashMap<String, List<String>> WELL_CHANNEL_MAP = new ConcurrentHashMap<>(16);

    /**
     * 客户端与频道绑定
     */
    private final static ConcurrentHashMap<String, ChannelId> CHANNEL_MAP = new ConcurrentHashMap<>(16);

    /**
     * 存储频道
     */
    public final static ChannelGroup CHANNEL_GROUP = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);

    /**
     * 重入锁
     */
    private static final Lock LOCK = new ReentrantLock();

    /**
     * 获取单机连接数量
     */
    public static int getLocalConnectCount() {
        return CHANNEL_GROUP.size();
    }

    /**
     * 获取绑定的通道数量（测试用）
     */
    public static int getBindCount() {
        return CHANNEL_MAP.size();
    }

    /**
     * 绑定频道和客户端id
     *
     * @param ctx      连接频道
     * @param wellId 井号
     * @param clientId 用户id
     */
    public static void bind(ChannelHandlerContext ctx,String wellId, String clientId) {
        LOCK.lock();
        try {
            // 释放旧的连接
            closeAndClean(clientId);
            // 绑定客户端id到频道上
            ctx.channel().attr(CLIENT_ID).set(clientId);
            ctx.channel().attr(WELL_ID).set(wellId);
            // 双向保存客户端id和频道
            CHANNEL_MAP.put(clientId, ctx.channel().id());
            List<String> channelIdList = WELL_CHANNEL_MAP.getOrDefault(wellId,null);
            if(null == channelIdList){
                channelIdList = Collections.synchronizedList(new ArrayList<>());
                WELL_CHANNEL_MAP.put(wellId,channelIdList);
            }
            else{
                // 清除绑定关系
                if(channelIdList.indexOf(clientId)!=-1){
                    channelIdList.remove(clientId);
                }
            }

            channelIdList.add(clientId);
            // 保存频道
            CHANNEL_GROUP.add(ctx.channel());
        } finally {
            LOCK.unlock();
        }
    }

    public static void setIsPull(ChannelHandlerContext ctx,Boolean isPull){
        try {
            ctx.channel().attr(IS_PULL).set(isPull);
        }catch (Exception e){

        }

    }

    public static void setIsWarningPull(ChannelHandlerContext ctx,Boolean isWarningPull){
        try {
            ctx.channel().attr(IS_WARNING_PULL).set(isWarningPull);
        }catch (Exception e){

        }

    }


    /**
     * 是否已登录
     */
    public static boolean isAuth(ChannelHandlerContext ctx) {
        return !StringUtil.isNullOrEmpty(getClientId(ctx));
    }

    /**
     * 获取客户端id
     *
     * @param ctx 连接频道
     */
    public static String getClientId(ChannelHandlerContext ctx) {
        return ctx.channel().hasAttr(CLIENT_ID) ? (String) ctx.channel().attr(CLIENT_ID).get() : "";
    }

    /**
     * 获取绑定特定井号的客户端集
     *
     * @param wellId 井id
     */
    public static List<String> getClientListByWellId(String wellId) {
        return  WELL_CHANNEL_MAP.getOrDefault(wellId,null);
    }

    /**
     * 获取所有客户端集
     *
     */
    public static Enumeration<String> getAllClients() {
        return  CHANNEL_MAP.keys();
    }

    /**
     * 获取客户端wellid
     *
     * @param ctx 连接频道
     */
    public static String getWellId(ChannelHandlerContext ctx) {
        return ctx.channel().hasAttr(WELL_ID) ? (String) ctx.channel().attr(WELL_ID).get() : "";
    }
    /**
     * 获取当前连接是否可以推送
     */
    public static Boolean getIsPull(Channel channel){
        return channel.hasAttr(IS_PULL) ?  channel.attr(IS_PULL).get() : false;
    }

    /**
     * 获取当前连接是否可以推送
     */
    public static Boolean getIsWarningPull(Channel channel){
        return channel.hasAttr(IS_WARNING_PULL) ?  channel.attr(IS_WARNING_PULL).get() : false;
    }

    /**
     * 获取频道
     *
     * @param clientId 客户端id
     */
    public static Channel getChannel(String clientId) {
        return Optional.of(CHANNEL_MAP.containsKey(clientId))
                .filter(Boolean::booleanValue)
                .map(b -> CHANNEL_MAP.get(clientId))
                .map(CHANNEL_GROUP::find)
                .orElse(null);
    }

    /**
     * 释放连接和资源
     * CLIENT_CHANNEL_MAP 需要释放
     * CHANNEL_GROUP 不需要释放，netty会自动帮我们移除
     *
     * @param clientId 客户端id
     */
    public static void closeAndClean(String clientId) {
        // 清除绑定关系
        Optional.of(CHANNEL_MAP.containsKey(clientId))
                .filter(Boolean::booleanValue)
                .ifPresent(oldChannel -> CHANNEL_MAP.remove(clientId));
        Optional.ofNullable(getChannel(clientId))
                .ifPresent(ChannelOutboundInvoker::close);
    }

    public static void closeAndClean(ChannelHandlerContext ctx) {
        String wellId = getWellId(ctx);
        String clientId = getClientId(ctx);
        if(wellId != null){
            List<String> channelIdList = WELL_CHANNEL_MAP.getOrDefault(wellId,null);
            if(null != channelIdList){
                if(channelIdList.contains(clientId)){
                    channelIdList.remove(clientId);
                }
                if(channelIdList.size() == 0){
                    WELL_CHANNEL_MAP.remove(wellId);
                }
            }
        }

        closeAndClean(clientId);
    }

    public static ConcurrentHashMap<String, List<String>> getWellMap(){
        return WELL_CHANNEL_MAP;
    }

}
