package org.framework.lazy.cloud.network.heartbeat.server.netty.flow;

import io.netty.channel.Channel;
import org.framework.lazy.cloud.network.heartbeat.common.advanced.flow.AbstractHandleChannelFlowAdvanced;
import org.framework.lazy.cloud.network.heartbeat.common.advanced.flow.ChannelFlow;
import org.framework.lazy.cloud.network.heartbeat.common.enums.ChannelFlowEnum;
import org.framework.lazy.cloud.network.heartbeat.server.properties.ServerNodeProperties;
import org.framework.lazy.cloud.network.heartbeat.server.standalone.application.LazyVisitorPortFlowApplication;
import org.framework.lazy.cloud.network.heartbeat.server.standalone.application.command.visitor.flow.LazyVisitorPortFlowStoryCommand;

/**
 * 进口流量处理
 */
public class ServerHandlerInFlowHandler extends AbstractHandleChannelFlowAdvanced {
    private final LazyVisitorPortFlowApplication lazyVisitorPortFlowApplication;
    private final ServerNodeProperties serverNodeProperties;

    public ServerHandlerInFlowHandler(LazyVisitorPortFlowApplication lazyVisitorPortFlowApplication, ServerNodeProperties serverNodeProperties) {
        this.lazyVisitorPortFlowApplication = lazyVisitorPortFlowApplication;
        this.serverNodeProperties = serverNodeProperties;
    }

    /**
     * 处理是否支持这种类型
     *
     * @param channelFlow 数据
     * @return boolean
     */
    @Override
    protected boolean doSupport(ChannelFlow channelFlow) {
        if (serverNodeProperties.getEnableFlowControl()) {
            return ChannelFlowEnum.IN_FLOW.equals(channelFlow.channelFlowEnum());
        } else {
            return false;
        }
    }

    /**
     * 处理当前数据
     *
     * @param channel     当前通道
     * @param channelFlow 通道数据
     */
    @Override
    protected void doHandler(Channel channel, ChannelFlow channelFlow) {
        String clientId = channelFlow.clientId();
        Integer port = channelFlow.port();
        Integer flow = channelFlow.flow();

        // 进口流量处理
        LazyVisitorPortFlowStoryCommand visitorPortFlow = new LazyVisitorPortFlowStoryCommand();
        visitorPortFlow.setInFlow(flow);
        visitorPortFlow.setClientId(clientId);
        visitorPortFlow.setVisitorPort(port);
        visitorPortFlow.setIsDeleted(false);
        lazyVisitorPortFlowApplication.flowIncreaseStory(visitorPortFlow);
    }
}
