package org.framework.lazy.cloud.network.heartbeat.common.pool;

import io.netty.channel.Channel;
import org.framework.lazy.cloud.network.heartbeat.common.utils.ChannelAttributeKeyUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;

/**
 * 默认netty 连接池
 */
public class DefaultNettyChannelPool extends AbstractNettyChannelPool implements NettyChannelPool {

    /**
     * 连接池大小
     */
    private final int poolSize;


    // 绑定访客的通道
    private final ConcurrentHashMap<String, Channel> visitorChannelMap = new ConcurrentHashMap<>();

    // 所有的通道
    private final List<Channel> allChannelList = new ArrayList<>();

    // 闲置的通道
    private final List<Channel> idleChannelList = new CopyOnWriteArrayList<Channel>();

    public DefaultNettyChannelPool(int poolSize) {
        this.poolSize = poolSize;
    }

    /**
     * 根据访客ID获取可以使用的通道
     *
     * @param visitorId 访客ID
     * @return Channel 如果无法获取到闲置通道返回null
     */
    @Override
    public Channel availableChannel(String visitorId) {
        synchronized (idleChannelList) {
            if (idleChannelList.isEmpty()) {
                return null;
            }
            // 获取通道
            Channel visitorChannel = null;
            for (Channel idleChannel : idleChannelList) {
                if (idleChannel.isActive()) {
                    visitorChannel = idleChannel;
                }
                idleChannelList.remove(idleChannel);
            }
            if (visitorChannel == null) {
                return null;
            }
            // 绑定 通道
            ChannelAttributeKeyUtils.buildVisitorId(visitorChannel, visitorId);
            visitorChannelMap.put(visitorId, visitorChannel);
            return visitorChannel;
        }

    }
}
