package org.matrix.socket;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONException;
import org.matrix.actuators.usecase.CaseActuator;
import org.matrix.database.service.ITestDataService;
import org.matrix.socket.enums.SocketType;
import org.matrix.socket.pool.MonitorSocketPool;
import org.matrix.socket.vo.CaseExecuteVo;
import org.matrix.socket.vo.ExecuteMonitorVo;
import org.matrix.socket.vo.SocketVo;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

/**
 * webSocket处理 调用和执行的日志发送
 *
 * @author huangxiahao
 */
@Component
public class ExecutionSocketHandler extends TextWebSocketHandler {

    public static final MonitorSocketPool EXECUTE_MONITOR_SOCKET_POOL = new MonitorSocketPool();

    final CaseActuator caseActuator;
    final ITestDataService testDataService;

    public ExecutionSocketHandler(CaseActuator caseActuator, ITestDataService testDataService) {
        this.caseActuator = caseActuator;
        this.testDataService = testDataService;
    }

    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        String payload = message.getPayload();
        //检验客户端是否进行测试用例调试
        try {
            SocketVo socketVo = JSON.parseObject(payload, SocketVo.class);
            //如果客户端发送测试用例调试命令，则进行测试用例的执行
            if (socketVo != null && socketVo.getSocketType() != null) {
                if (SocketType.TEST_CASE_EXECUTE.equals(socketVo.getSocketType())) {
                    CaseExecuteVo caseExecuteVo = JSON.parseObject(payload, CaseExecuteVo.class);
                    caseActuator.runTestCase(session, caseExecuteVo);
                } else if (SocketType.TEST_CASE_MONITOR.equals(socketVo.getSocketType())) {
                    ExecuteMonitorVo caseExecuteVo = JSON.parseObject(payload, ExecuteMonitorVo.class);
                    EXECUTE_MONITOR_SOCKET_POOL.add(caseExecuteVo.getUniqueKey(), session);
                } else {
                    session.sendMessage(new TextMessage("入参不符合规定"));
                }
            }
        } catch (JSONException e) {
            session.sendMessage(new TextMessage("入参不符合规定"));
        }
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) {
        EXECUTE_MONITOR_SOCKET_POOL.remove(session);
    }



}
