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


import io.netty.channel.Channel;
import io.netty.channel.ChannelId;
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.NettyClientVisitorContext;
import org.framework.lazy.cloud.network.heartbeat.common.NettyProxyMsg;
import org.framework.lazy.cloud.network.heartbeat.common.advanced.server.AbstractHandleReportDisconnectTypeAdvanced;
import org.framework.lazy.cloud.network.heartbeat.server.netty.socket.NettyServerPermeateClientVisitorSocket;
import org.framework.lazy.cloud.network.heartbeat.server.standalone.application.LazyClientStatsChangeApplication;
import org.springframework.stereotype.Component;
import org.wu.framework.core.utils.ObjectUtils;

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


/**
 * 服务端处理客户端断开连接处理
 * TYPE_DISCONNECT
 */
@Slf4j
@Component
public class ServerHandleReportDisconnectTypeAdvanced extends AbstractHandleReportDisconnectTypeAdvanced<NettyProxyMsg> {
    private final LazyClientStatsChangeApplication lazyClientStatsChangeApplication;

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

    /**
     * 处理当前数据
     *
     * @param deathChannel 关闭的通道
     * @param msg          通道数据
     */
    @Override
    public void doHandler(Channel deathChannel, NettyProxyMsg msg) {
        // 关闭连接通知
        byte[] clientId = msg.getClientId();
        log.warn("close client :{} channel", new String(clientId));
        Channel deathClientChannelDTO = ChannelContext.getLoadBalance(clientId);

        if (deathClientChannelDTO != null) {
            // 服务状态离线
            String tenantId = new String(clientId);
            lazyClientStatsChangeApplication.clientOffLine(tenantId);
            ChannelContext.remove(clientId);

            // 通知其他客户端 channelId 关闭了
            ChannelContext.getChannels().forEach((existClientId, channels) -> {
                for (Channel channel : channels) {
                    // 离线通知
                    NettyProxyMsg nettyMsg = new NettyProxyMsg();
                    nettyMsg.setType(MessageType.DISTRIBUTE_CLIENT_DISCONNECTION_NOTIFICATION);
                    nettyMsg.setClientId(clientId);
                    nettyMsg.setData(clientId);
                    channel.writeAndFlush(nettyMsg);
                    // 暂存通知
                    NettyProxyMsg stagingNettyProxyMsg = new NettyProxyMsg();
                    stagingNettyProxyMsg.setType(MessageType.DISTRIBUTE_CLIENT_STAGING_OPENED_NOTIFICATION);
                    stagingNettyProxyMsg.setData(clientId);
                    stagingNettyProxyMsg.setClientId(clientId);
                    channel.writeAndFlush(stagingNettyProxyMsg);
                }

            });
            // 关闭绑定的访客端口
            List<NettyServerPermeateClientVisitorSocket> visitorSockets = NettyClientVisitorContext.getVisitorSockets(new String(clientId));
            if (!ObjectUtils.isEmpty(visitorSockets)) {
                for (NettyServerPermeateClientVisitorSocket visitorSocket : visitorSockets) {
                    int visitorPort = visitorSocket.getVisitorPort();
                    visitorSocket.close();
                    log.warn("client :[{}] visitorPort:[{}] close", new String(clientId), visitorPort);
                }
            }

        }
    }


}
