package net.northking.cctp.se.debugger;


import com.fasterxml.jackson.databind.ObjectMapper;
import net.northking.cctp.se.dto.*;
import net.northking.cctp.se.script.ATUScript;
import net.northking.cctp.se.script.ScriptStep;

import javax.websocket.Session;
import java.io.IOException;

/**
 * 基于WebSocket通讯协议的自动化测试调试器
 */
public abstract class WebSocketATUDebugger extends ATUDebuggerLifecycle<Session>
{
  /**
   * JSON 序列化工具
   */
  private static ObjectMapper objectMapper = new ObjectMapper();

  public WebSocketATUDebugger(String id, Session nativeClient)
  {
    super(id, nativeClient);
  }

  /**
   * 推送指令结果或者日志
   *
   * @param message 推送消息
   * @throws IOException 异常
   */
  public void send(Object message)
  {
    try
    {
      String text = objectMapper.writeValueAsString(message);
      nativeClient.getBasicRemote().sendText(text);
    } catch (IOException e)
    {
      // TODO 推送指令或者日志失败
    }
  }

  private ATUWebSocketReplay replayRequest;

  public void replay(ATUWebSocketReplay replayRequest)
  {
    this.replayRequest = replayRequest;
  }

  @Override
  public String getReplayType()
  {
    return replayRequest.getType();
  }

  @Override
  public String targetStepId()
  {
    return replayRequest.getStepId();
  }

  @Override
  public ATUScript getScript()
  {
    return replayRequest.getScript();
  }


  /**
   * 推送日志
   *
   * @param atuLog 日志
   */
  protected void logger(ATULog atuLog)
  {
    ATUWebSocketMessage<ATULog> message = new ATUWebSocketMessage<ATULog>();

    message.setCmd("log");
    message.setData(atuLog);
    send(message);
  }

  /**
   *
   * @param scriptStep
   */
  @Override
  protected void beforeReplayScriptStep(ScriptStep scriptStep)
  {

  }

  @Override
  protected void afterReplayScriptStep(ScriptStep scriptStep, Object stepResult)
  {

  }
}
