package com.red.circle.game.fruit.infrastructure.websocket.config;

import com.red.circle.game.fruit.core.token.AnalysisToken;
import com.red.circle.tool.core.text.StringUtils;
import jakarta.servlet.http.HttpServletRequest;
import java.util.Map;
import lombok.RequiredArgsConstructor;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.HandshakeInterceptor;

/**
 * websocket 握手检查.
 *
 * @author pengliang on 2021/7/20
 */
@Configuration
@RequiredArgsConstructor
public class SocketHandshakeInterceptor implements HandshakeInterceptor {

  private final AnalysisToken analysisToken;

  @Override
  public boolean beforeHandshake(ServerHttpRequest request,
      ServerHttpResponse response,
      WebSocketHandler wsHandler,
      Map<String, Object> attributes) {
    ServletServerHttpRequest servletServerHttpRequest = (ServletServerHttpRequest) request;
    HttpServletRequest httpRequest = servletServerHttpRequest.getServletRequest();
    final String token = httpRequest.getParameter(SocketConstant.TOKEN);
    final String destination = httpRequest.getParameter(SocketConstant.DESTINATION);
    if (StringUtils.isBlank(token)) {
      return false;
    }

    String userId = analysisToken.getUserId(token);
    if (StringUtils.isBlank(userId)) {
      return false;
    }

    attributes.put(SocketConstant.TOKEN, token);
    attributes.put(SocketConstant.USER_ID, userId);

    if (StringUtils.isNotBlank(destination)) {
      attributes.put(SocketConstant.DESTINATION, destination);
    }
    return true;
  }

//  private Long getUserId(String token) {
//    try {
//      return UserCredential.parseToken(token).getUserId();
//    } catch (Exception ignore) {
//      // ignore
//    }
//    return null;
//  }

  @Override
  public void afterHandshake(ServerHttpRequest request, ServerHttpResponse
      response, WebSocketHandler wsHandler, Exception exception) {
  }

}
