package org.framework.lazy.cloud.network.heartbeat.client.context;

import jakarta.annotation.PreDestroy;
import lombok.extern.slf4j.Slf4j;
import org.framework.lazy.cloud.network.heartbeat.client.application.LazyNettyServerPropertiesApplication;
import org.framework.lazy.cloud.network.heartbeat.client.config.NettyClientProperties;
import org.framework.lazy.cloud.network.heartbeat.client.config.PropertiesType;
import org.framework.lazy.cloud.network.heartbeat.client.infrastructure.entity.LazyNettyServerPropertiesDO;
import org.framework.lazy.cloud.network.heartbeat.common.enums.ProtocolType;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.boot.context.event.ApplicationStartedEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;
import org.wu.framework.lazy.orm.database.lambda.stream.lambda.LazyLambdaStream;
import org.wu.framework.lazy.orm.database.lambda.stream.wrapper.LazyWrappers;

import java.util.Objects;

@Slf4j
@Component
public class NettyClientSocketApplicationListener implements ApplicationListener<ApplicationStartedEvent>, DisposableBean {


    private final NettyClientProperties nettyClientProperties;
    private final LazyLambdaStream lazyLambdaStream;

    private final LazyNettyServerPropertiesApplication lazyNettyServerPropertiesApplication;

    public NettyClientSocketApplicationListener(NettyClientProperties nettyClientProperties, LazyLambdaStream lazyLambdaStream, LazyNettyServerPropertiesApplication lazyNettyServerPropertiesApplication) {
        this.nettyClientProperties = nettyClientProperties;
        this.lazyLambdaStream = lazyLambdaStream;
        this.lazyNettyServerPropertiesApplication = lazyNettyServerPropertiesApplication;
    }

    /**
     * 存储配置到db
     */
    public void initDb2Config() {

      try {
          String clientId = nettyClientProperties.getClientId();
          String inetHost = nettyClientProperties.getInetHost();
          int inetPort = nettyClientProperties.getInetPort();
          String appKey = nettyClientProperties.getAppKey();
          String appSecret = nettyClientProperties.getAppSecret();
          ProtocolType protocolType = nettyClientProperties.getProtocolType();
          if (Objects.isNull(clientId) ||
                  Objects.isNull(inetHost)) {
              log.warn("配置信息为空，请通过页面添加配置信息:{}", nettyClientProperties);
              return;
          }
          LazyNettyServerPropertiesDO lazyNettyServerPropertiesDO = new LazyNettyServerPropertiesDO();
          lazyNettyServerPropertiesDO.setClientId(clientId);
          lazyNettyServerPropertiesDO.setInetHost(inetHost);
          lazyNettyServerPropertiesDO.setInetPort(inetPort);
          lazyNettyServerPropertiesDO.setType(PropertiesType.CONFIG);
          lazyNettyServerPropertiesDO.setIsDeleted(false);
          lazyNettyServerPropertiesDO.setAppKey(appKey);
          lazyNettyServerPropertiesDO.setAppSecret(appSecret);
          lazyNettyServerPropertiesDO.setProtocolType(protocolType);


          // 根据服务端端口、port 唯一性验证
          boolean exists = lazyLambdaStream.exists(LazyWrappers.<LazyNettyServerPropertiesDO>lambdaWrapper()
                  .eq(LazyNettyServerPropertiesDO::getInetHost, inetHost)
                  .eq(LazyNettyServerPropertiesDO::getInetPort, inetPort)
                  .eq(LazyNettyServerPropertiesDO::getClientId, clientId)
                  .eq(LazyNettyServerPropertiesDO::getProtocolType, protocolType)
          );
          if (!exists) {
              lazyLambdaStream.insert(lazyNettyServerPropertiesDO);
          }
      }catch (Exception e){
          e.printStackTrace();
      }
    }



    /**
     * Handle an application event.
     *
     * @param event the event to respond to
     */
    @Override
    public void onApplicationEvent(ApplicationStartedEvent event) {
        try {
            // 存储配置到db
            initDb2Config();
            // 启动客户端连接
            lazyNettyServerPropertiesApplication.starterAllClientSocket();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    @PreDestroy
    @Override
    public void destroy() throws Exception {
        lazyNettyServerPropertiesApplication.destroyClientSocket();
    }

}