package com.gxwebsoft.common.core.socketio.config;

import com.corundumstudio.socketio.SocketIOServer;
import com.gxwebsoft.common.core.config.ConfigProperties;
import com.gxwebsoft.common.core.security.JwtSubject;
import com.gxwebsoft.common.core.security.JwtUtil;
import com.gxwebsoft.common.core.socketio.cache.ClientCache;
import com.gxwebsoft.common.core.socketio.handler.SocketIOHandler;
import com.gxwebsoft.common.system.entity.User;
import com.gxwebsoft.common.system.service.UserService;
import io.jsonwebtoken.Claims;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.io.InputStream;

/**
 * socket服务配置
 * @author machenike
 */
@Configuration
public class SocketIOConfig implements InitializingBean {

  private final static Logger logger = LoggerFactory.getLogger(SocketIOConfig.class);
  @Value("${socketio.host}")
  private String host;

  @Value("${socketio.port}")
  private Integer port;

  @Resource
  private SocketIOHandler socketIOHandler;

  @Resource
  private UserService userService;

  @Resource
  private ConfigProperties configProperties;

  @Override
  public void afterPropertiesSet() throws Exception {
    com.corundumstudio.socketio.Configuration config = new com.corundumstudio.socketio.Configuration();
    //设置host
    config.setHostname(host);
    //设置端口
    config.setPort(port);
    config.setBossThreads(1);
    config.setAuthorizationListener(handshakeData -> {
      String userId =handshakeData.getSingleUrlParam("userId");
      String token = handshakeData.getSingleUrlParam("token");
      logger.info("身份验证 token：{}", token);
      if(!StringUtils.hasText(token) || !StringUtils.hasText(userId)){
        return false;
      }
      //  身份验证
      Claims claims = JwtUtil.parseToken(token, configProperties.getTokenKey());
      JwtSubject jwtSubject = JwtUtil.getJwtSubject(claims);
      User user = userService.getByUsername(jwtSubject.getUsername(), jwtSubject.getTenantId());

      if (user == null || !user.getUserId().equals(Integer.valueOf(userId))) {
        return false;
      }
      return true;
    });

        InputStream resourceAsStream = this.getClass().getResourceAsStream("/jks/love.jks");  // 读取证书文件流
        config.setKeyStore(resourceAsStream);  // 设置证书文件
        config.setKeyStorePassword("123456");  // 设置证书密码

    // 启动socket服务
//    SocketIOServer server = new SocketIOServer(config);
//    server.addListeners(socketIOHandler);
//    server.start();
//    ClientCache.setSocketIOServer(server);
//    logger.debug("Netty SocketIO启动：{}:{}",host,port);
  }
}
