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

import net.northking.cctp.se.debugger.PCUIDebugger;
import net.northking.cctp.se.dto.ATUWebSocketReplay;
import net.northking.cctp.se.thread.ExecutorPool;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

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

import static javax.websocket.CloseReason.CloseCodes.CANNOT_ACCEPT;

public class WebSocketPCUIDebuggerPool implements WebSocketDebuggerPool
{
  public static final Logger logger = LoggerFactory.getLogger(WebSocketPCUIDebuggerPool.class);

  private static WebSocketPCUIDebuggerPool instance = new WebSocketPCUIDebuggerPool();

  private WebSocketPCUIDebuggerPool()
  {
  }

  public static WebSocketPCUIDebuggerPool getInstance()
  {
    return instance;
  }

  /**
   * 最大在线客户端数量
   */
  private static final int MAX_ONLINE_CLIENT = 1;

  private PCUIDebugger debugger;


  @Override
  public void createDebugger(Session session, String deviceToken)
  {
    //校验PCUI自动化线程是否开启创建
    if(!ExecutorPool.enablePc){
      try {
        session.close(new CloseReason(CANNOT_ACCEPT, "PCUI自动化引擎连接已禁用，拒绝连接"));
      } catch (IOException e) {
        logger.info("拒绝创建调试器。关闭会话失败！", e);
      }
    }

    if (debugger == null || debugger.isClosed())
    {
      debugger = new PCUIDebugger(deviceToken, session);
    } else if (deviceToken.equals(debugger.getId()))
    {
      debugger.setNativeClient(session);
    } else
    {// 拒绝创建【PC端UI自动化测试调试器】
      try
      {
        session.close(new CloseReason(CANNOT_ACCEPT, ""));
      } catch (IOException e)
      {
        logger.error("拒绝创建调试器。关闭会话失败！", e);
      }
    }
  }

  @Override
  public void destroyDebugger(String deviceToken)
  {
    if (debugger.getId().equals(deviceToken))
    {
      debugger.close();
    }
  }

  @Override
  public void replayStart(String deviceToken, ATUWebSocketReplay replayRequest)
  {
    if (debugger.isStopped())
    {
      debugger.replay(replayRequest);
      Thread debuggerThread = new Thread(debugger);
      debuggerThread.setDaemon(true);
      debuggerThread.start();
    }

  }

  @Override
  public void replayStop(String deviceToken)
  {
    if (debugger.getId().equals(deviceToken))
    {
      debugger.stop();
    }
  }

  /**
   * 访问线程池
   * @return
   */
  public PCUIDebugger getPoolInfo(){
    return debugger;
  }
}
