package com.m2pool.lease.netty.handler;

import io.netty.channel.Channel;

import java.util.Map;
import java.util.Optional;
import java.util.concurrent.ConcurrentHashMap;


/**
 * @Description 频道管理类
 * @Date 2025/11/25 15:07
 * @Author yyb
 */
public class ChannelManager {

    /**
     * key ip    value channel
     */
    private static final Map<String, Channel> channelMap = new ConcurrentHashMap<>();

    /**
     * key channel value id
     */
    public static final Map<Channel, String> idMap  = new ConcurrentHashMap<>();

    /**
     * 添加Channel
     * @param ip
     * @param channel
     */
    public static void addChannel(String ip, Channel channel) {
        Channel prev = channelMap.put(ip, channel);
        if (prev != null && prev.isActive()) {
            prev.close();
        }
    }

    /**
     * 移除Channel
     * @param ip
     */
    public static void removeChannel(String ip) {
        Channel channel = channelMap.get(ip);
        if (channel != null){
            idMap.remove(channel);
            channelMap.remove(ip);
        }


    }



    public static String getIdByChannel(String ip) {
        Channel channel = channelMap.get(ip);
        if (channel != null){
            return idMap.get(channel);
        }
        return null;
    }

    /**
     * 根据id: 邮箱::mac地址获取Channel
     * @param id
     * @return
     */
    public static Channel getChannelById(String id) {
        Optional<Channel> key = idMap.entrySet()
                .stream()
                .filter(entry -> id.equals(entry.getValue()))
                .map(Map.Entry::getKey)
                .findFirst();
        return key.orElse(null);
    }
    public static boolean sendToClient(String id, Object message) {
        Channel channel = getChannelById(id);
        if (channel != null && channel.isActive()) {
            channel.writeAndFlush(message).syncUninterruptibly();
            return false;
        }else{
            return true;
        }
    }

}
