package org.framework.lazy.cloud.network.heartbeat.server.cluster.event;


import io.netty.channel.Channel;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.framework.lazy.cloud.network.heartbeat.client.domain.model.lazy.netty.server.properties.LazyNettyServerProperties;
import org.framework.lazy.cloud.network.heartbeat.client.domain.model.lazy.netty.server.properties.LazyNettyServerPropertiesRepository;
import org.framework.lazy.cloud.network.heartbeat.client.netty.event.ClientChangeEvent;
import org.framework.lazy.cloud.network.heartbeat.common.constant.TcpMessageType;
import org.framework.lazy.cloud.network.heartbeat.common.NettyClientChannel;
import org.framework.lazy.cloud.network.heartbeat.common.NettyProxyMsg;
import org.framework.lazy.cloud.network.heartbeat.common.NettyServerContext;
import org.framework.lazy.cloud.network.heartbeat.common.enums.NettyClientStatus;
import org.framework.lazy.cloud.network.heartbeat.server.cluster.domain.model.cluster.node.LazyNettyClusterNodeRepository;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * node 注册 变更事件
 */
@Primary
@Slf4j
@Component
public class ClusterNodeChangeEventImpl implements ClientChangeEvent {


    @Resource
    private LazyNettyServerPropertiesRepository lazyNettyServerPropertiesRepository;

    @Resource
    private LazyNettyClusterNodeRepository lazyNettyClusterNodeRepository;


//    private final StringRedisTemplate stringRedisTemplate;
//    private final RedisProviderTemplate redisProviderTemplate;
//
//    public DefaultClientChangeEvent1Impl(StringRedisTemplate stringRedisTemplate, RedisProviderTemplate redisProviderTemplate) {
//        this.stringRedisTemplate = stringRedisTemplate;
//        this.redisProviderTemplate = redisProviderTemplate;
//    }


    /**
     * 推送客户端在线
     */
    @Override
    public void clientOnLine(String clientId) {
//        // 获取当前客户端ID
//        if (ObjectUtils.isEmpty(clientId)) {
//            clientId = stringRedisTemplate.opsForValue().get(ClientConfigKeyUtils.CLIENT_ID_KEY);
//        }
//        String clientStatusKey = ClientConfigKeyUtils.getClientStatusKey(clientId);
//        // 如果可以已经在线状态不推送
//        stringRedisTemplate.opsForValue().set(clientStatusKey, NettyClientStatus.ON_LINE.name());
//        ClientOnLineState clientOnLineState = new ClientOnLineState();
//        clientOnLineState.setClientId(clientId);
//        clientOnLineState.setOnLineState(NettyClientStatus.ON_LINE.name());
//        // 暂存扫描触发
//        redisProviderTemplate.send(RedisChannelConstant.REDIS_CLIENT_ONLINE_OR_OFFLINE_CHANNEL,clientOnLineState);

    }

    /**
     * 推送客户端在线
     *
     * @param inetHost 服务端ip
     * @param inetPort 服务端端口
     * @param serverId 服务端ID
     * @param clientId 客户端
     */
    @Override
    public void clientOnLine(String inetHost, int inetPort, String serverId, String clientId) {
        LazyNettyServerProperties lazyNettyServerProperties = new LazyNettyServerProperties();
        lazyNettyServerProperties.setClientId(clientId);
        lazyNettyServerProperties.setInetHost(inetHost);
        lazyNettyServerProperties.setInetPort(inetPort);
        lazyNettyServerProperties.setConnectStatus(NettyClientStatus.ON_LINE);
        lazyNettyServerPropertiesRepository.onLine(lazyNettyServerProperties);
        // 更改状态在线
        clientOnLine(clientId);

        List<NettyClientChannel> serverEndpointChannels = NettyServerContext.getServerEndpointChannels();
        for (NettyClientChannel serverEndpointChannel : serverEndpointChannels) {
            Channel serverEndpointChannelChannel = serverEndpointChannel.getChannel();
            if (serverEndpointChannelChannel != null && serverEndpointChannelChannel.isActive()) {
                // 客户端本地获取所有 已经连接的服务端的channel 通知他们 扫描数据库node信息，重新初始化
                NettyProxyMsg nettyMsg = new NettyProxyMsg();
                nettyMsg.setType(TcpMessageType.TCP_REPORT_CLUSTER_NODE_REGISTER_MESSAGE);
                nettyMsg.setClientId(clientId);
                nettyMsg.setData((clientId).getBytes());
                serverEndpointChannelChannel.writeAndFlush(nettyMsg);
            }
        }

        // 修改节点状态
        lazyNettyClusterNodeRepository.updateNodeStatus(serverId);


    }



    /**
     * 推送客户端离线
     */
    @Override
    public void clientOffLine(String clientId) {
//        if (ObjectUtils.isEmpty(clientId)) {
//            clientId = stringRedisTemplate.opsForValue().get(ClientConfigKeyUtils.CLIENT_ID_KEY);
//        }
//        String clientStatusKey = ClientConfigKeyUtils.getClientStatusKey(clientId);
//        // 离线状态
//        stringRedisTemplate.opsForValue().set(clientStatusKey, NettyClientStatus.OFF_LINE.name());
//        // 暂存状态
//        stagingOpen(clientId);
//        // 暂存扫描触发
//        ClientOnLineState clientOnLineState = new ClientOnLineState();
//        clientOnLineState.setClientId(clientId);
//        clientOnLineState.setOnLineState(NettyClientStatus.OFF_LINE.name());
//        redisProviderTemplate.send(RedisChannelConstant.REDIS_CLIENT_ONLINE_OR_OFFLINE_CHANNEL,clientOnLineState);
    }

    /**
     * 推送客户端离线
     *
     * @param inetHost 服务端ip
     * @param inetPort 服务端端口
     * @param serverId
     * @param clientId 客户端
     */
    @Override
    public void clientOffLine(String inetHost, int inetPort, String serverId, String clientId) {
        LazyNettyServerProperties lazyNettyServerProperties = new LazyNettyServerProperties();
        lazyNettyServerProperties.setClientId(clientId);
        lazyNettyServerProperties.setInetHost(inetHost);
        lazyNettyServerProperties.setInetPort(inetPort);
        lazyNettyServerProperties.setConnectStatus(NettyClientStatus.OFF_LINE);
        lazyNettyServerPropertiesRepository.offLine(lazyNettyServerProperties);
        clientOffLine(clientId);
        // 修改节点状态
        lazyNettyClusterNodeRepository.updateNodeStatus(serverId);
    }

    @Override
    public void stagingOpen(String clientId) {
//        String stagingStatusKey = StagingConfigKeyConstant.getStagingStatusKey(clientId);
//        stringRedisTemplate.opsForValue().set(stagingStatusKey, StagingStatus.OPENED.name());

    }

    /**
     * 暂存关闭
     *
     * @param clientId 租户ID
     */
    @Override
    public void stagingClose(String clientId) {
//        if (clientId == null) {
//            clientId = stringRedisTemplate.opsForValue().get(ClientConfigKeyUtils.CLIENT_ID_KEY);
//        }
//        String stagingStatusKey = StagingConfigKeyConstant.getStagingStatusKey(clientId);
//        stringRedisTemplate.opsForValue().set(stagingStatusKey, StagingStatus.CLOSED.name());

    }

}
