package org.matrix.socket;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONException;
import org.junit.platform.commons.util.StringUtils;
import org.matrix.actuators.usecase.CaseActuator;
import org.matrix.actuators.util.ThreadUtil;
import org.matrix.database.entity.TestCaseListDataBto;
import org.matrix.database.service.ITestDataService;
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;

import java.util.List;
import java.util.UUID;

/**
 * webSocket处理
 *
 * @author huangxiahao
 */
@Component
public class HttpAuthHandler extends TextWebSocketHandler {

    final CaseActuator caseActuator;
    final ITestDataService testDataService;

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


    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        session.sendMessage(new TextMessage("message get success"));
        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())) {
                    runTestCase(session, payload);
                }else if (SocketType.TEST_CASE_MONITOR.equals(socketVo.getSocketType())){
                    ExecuteMonitorVo caseExecuteVo = JSON.parseObject(payload, ExecuteMonitorVo.class);
                    ExecuteMonitorSocketPool.add(caseExecuteVo.getUnionKey(),session);
                } else {
                    session.sendMessage(new TextMessage("入参不符合规定"));
                }
            }
        } catch (JSONException e) {
            session.sendMessage(new TextMessage("入参不符合规定"));
        }
        session.sendMessage(new TextMessage("message execute success"));
    }

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

    /**
     * 执行TestCase，并控制运行态日志池，进行日志的生成。
     */
    private void runTestCase(WebSocketSession session, String payload) {
        //将websocketSession 加入到socket池子中
        Long currentThreadId = ThreadUtil.currentThreadId();
        TestCaseExecuteSocketPool.add(currentThreadId, session);
        CaseExecuteVo caseExecuteVo = JSON.parseObject(payload, CaseExecuteVo.class);
        List<TestCaseListDataBto> testCaseListDataBtoList = caseExecuteVo.getTestCaseListDataBtoList();
        String unionKey = UUID.randomUUID().toString();
        for (TestCaseListDataBto testCaseListDataBto : testCaseListDataBtoList) {
            TestExecuteLog testExecuteLog = LogQueueRuntime
                    .initTestCaseLog(caseExecuteVo.getUserId()
                            ,testCaseListDataBto.getTestCase().getId()
                            , caseExecuteVo.getType()
                            , unionKey
                    );
            LogQueueRuntime.put(currentThreadId, testExecuteLog);
            //执行测试用例
            caseActuator.executeTestCases(testCaseListDataBto, caseExecuteVo.getEnvId(), caseExecuteVo.getProjectId());
        }
        //将本次产生的数据清除
        TestCaseExecuteSocketPool.remove(Thread.currentThread().getId());
        //将本次产生的日志从执行状态设为停止状态
        LogQueueRuntime.stopExecutionRecords(unionKey);
    }

}
