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

import io.netty.channel.Channel;
import lombok.extern.slf4j.Slf4j;
import org.framework.lazy.cloud.network.heartbeat.common.advanced.flow.ChannelFlow;
import org.framework.lazy.cloud.network.heartbeat.common.advanced.flow.HandleChannelFlowAdvanced;

import java.util.List;
import java.util.concurrent.*;

/**
 * 通道流量适配器
 *
 * @see HandleChannelFlowAdvanced
 */
@Slf4j
public class ChannelFlowAdapter {


    ThreadPoolExecutor CHANNEL_FLOW_ADAPTER_EXECUTOR =
            new ThreadPoolExecutor(20, 200, 3L, TimeUnit.MINUTES,
                    new LinkedBlockingDeque<>(500),new ThreadPoolExecutor.AbortPolicy());
    // 线程使用完后使用主线程执行



    protected final List<HandleChannelFlowAdvanced> handleChannelFlowAdvancedList;

    public ChannelFlowAdapter(List<HandleChannelFlowAdvanced> handleChannelFlowAdvancedList) {
        this.handleChannelFlowAdvancedList = handleChannelFlowAdvancedList;
    }

    /**
     * 处理当前数据
     *
     * @param channelFlow 通道数据
     */
    public void handler(Channel channel, ChannelFlow channelFlow) {
        for (HandleChannelFlowAdvanced handleChannelTypeAdvanced : handleChannelFlowAdvancedList) {
            if (handleChannelTypeAdvanced.support(channelFlow)) {
                try {
                    handleChannelTypeAdvanced.handler(channel, channelFlow);
                } catch (Exception e) {
                    log.error("流量统计失败:{}", e.getMessage());
                }
                return;
            }
        }
    }

    /**
     * 异步处理当前数据
     *
     * @param channelFlow 通道数据
     */
    public void asyncHandler(Channel channel, ChannelFlow channelFlow) {
     // TODO 流量并发异常
        CHANNEL_FLOW_ADAPTER_EXECUTOR.submit(() -> handler(channel, channelFlow));
    }

}
