package net.northking.cctp.se.debugger.endpoint;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import net.northking.cctp.se.debugger.pool.WebSocketPCUIDebuggerPool;
import net.northking.cctp.se.dto.ATUWebSocketMessage;
import net.northking.cctp.se.dto.ATUWebSocketReplay;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import java.util.Map;

/**
 * PC端UI自动化测试调试器 WebSocket服务端
 */
@Component
public class DebuggerPCUIWebSocketServer
{
  private static final Logger logger = LoggerFactory.getLogger(DebuggerPCUIWebSocketServer.class);

  /**
   * JSON 序列化工具
   */
  private static ObjectMapper objectMapper = new ObjectMapper();


  @OnOpen
  public void onOpen(
      Session session,
      @PathParam("deviceToken") String deviceToken)
  {
    WebSocketPCUIDebuggerPool.getInstance().createDebugger(session, deviceToken);
  }

  @OnClose
  public void onClose(@PathParam("deviceToken") String deviceToken)
  {
    WebSocketPCUIDebuggerPool.getInstance().destroyDebugger(deviceToken);
  }

  /**
   * 键名： 指令类型
   */
  public static final String KEY_CMD_TYPE = "cmd";

  /**
   * 命令： 开始回放
   */
  public static final String CMD_REPLAY_START = "replay_start";

  /**
   * 命令： 停止回放
   */
  public static final String CMD_REPLAY_STOP = "replay_stop";

  @OnMessage
  public void onMessage(
      Session session,
      @PathParam("deviceToken") String deviceToken,
      String text) throws JsonProcessingException
  {
    Map<String, Object> requestMap = objectMapper.readValue(text, Map.class);

    String cmdType = requestMap.get(KEY_CMD_TYPE).toString();

    if (CMD_REPLAY_START.equalsIgnoreCase(cmdType))
    {// 开始回放
      replayStart(deviceToken, text);
    } else if (CMD_REPLAY_STOP.equalsIgnoreCase(cmdType))
    {// 停止回放
      replayStop(deviceToken);
    }

  }

  protected void replayStart(String deviceToken, String text) throws JsonProcessingException
  {
    TypeReference<ATUWebSocketMessage<ATUWebSocketReplay>> typeReference = new TypeReference<ATUWebSocketMessage<ATUWebSocketReplay>>()
    {
    };
    ATUWebSocketMessage<ATUWebSocketReplay> message = objectMapper.readValue(text, typeReference);
    WebSocketPCUIDebuggerPool.getInstance().replayStart(deviceToken, message.getData());

  }

  protected void replayStop(String deviceToken)
  {
    WebSocketPCUIDebuggerPool.getInstance().replayStop(deviceToken);
  }


  @OnError
  public void onError(
      Session session,
      @PathParam("debuggerId") String debuggerId,
      Throwable error
  )
  {

    logger.error("OnError: 发生异常！【PC端UI自动化测试调试器】= " + debuggerId, error);

  }
}
