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

import io.netty.channel.Channel;
import lombok.extern.slf4j.Slf4j;
import org.framework.lazy.cloud.network.heartbeat.common.ChannelContext;
import org.framework.lazy.cloud.network.heartbeat.common.MessageType;
import org.framework.lazy.cloud.network.heartbeat.common.NettyProxyMsg;
import org.framework.lazy.cloud.network.heartbeat.common.advanced.server.AbstractHandleReportStagingOpenedTypeAdvanced;
import org.framework.lazy.cloud.network.heartbeat.server.standalone.application.LazyClientStatsChangeApplication;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;
import java.util.List;

/**
 * 服务端处理上报的暂存开启
 */
@Slf4j
@Component
public class ServerHandleReportStagingOpenedTypeAdvanced extends AbstractHandleReportStagingOpenedTypeAdvanced<NettyProxyMsg> {

    private final LazyClientStatsChangeApplication lazyClientStatsChangeApplication;

    public ServerHandleReportStagingOpenedTypeAdvanced(LazyClientStatsChangeApplication lazyClientStatsChangeApplication) {
        this.lazyClientStatsChangeApplication = lazyClientStatsChangeApplication;
    }

    /**
     * 处理当前数据
     *
     * @param stagingOpenedChannel 开启暂存的通道
     * @param msg                  通道数据
     */
    @Override
    protected void doHandler(Channel stagingOpenedChannel, NettyProxyMsg msg) {
        // 获取所有通道
        byte[] clientIdBytes = msg.getClientId();
        List<Channel> stagingOpenedClientChannel = ChannelContext.get(clientIdBytes);
        if (stagingOpenedClientChannel != null) {
            ChannelContext.getChannels().forEach((existClientId, channels) -> {
                for (Channel channel : channels) {
                    // 存储当前客户端暂存关闭
                    String clientId = new String(clientIdBytes);
                    lazyClientStatsChangeApplication.stagingOpened(clientId);
                    // 告诉他们 当前参数这个通道 暂存开启了
                    NettyProxyMsg nettyMsg = new NettyProxyMsg();
                    nettyMsg.setType(MessageType.DISTRIBUTE_CLIENT_STAGING_OPENED_NOTIFICATION);
                    nettyMsg.setData((clientId
                            .getBytes(StandardCharsets.UTF_8)));
                    nettyMsg.setClientId((clientId
                            .getBytes(StandardCharsets.UTF_8)));
                    channel.writeAndFlush(nettyMsg);
                }
            });
        }


    }
}
