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.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 HttpAuthHandler extends TextWebSocketHandler {

    final CaseActuator caseActuator;
    final ITestDataService testDataService;


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

    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        super.afterConnectionEstablished(session);
        System.out.println("连接成功了");
    }

    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        System.out.println("收到了： " + message.toString());
        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())) {
                    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);
                    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);
    }



}
