package org.matrix.actuators.usecase;

import com.alibaba.fastjson.JSON;
import org.matrix.actuators.Actuator;
import org.matrix.actuators.checkpoint.CheckPointActuator;
import org.matrix.actuators.checkpoint.JsonPathCheckPoint;
import org.matrix.actuators.httpclient.HttpClientActuator;
import org.matrix.config.HttpRequestConfig;
import org.matrix.database.entity.TestCase;
import org.matrix.actuators.checkpoint.CheckPoint;
import org.matrix.actuators.checkpoint.CheckPointResult;
import org.matrix.actuators.httpclient.HttpRequestDetail;
import org.matrix.actuators.httpclient.HttpResponseDetail;

/**
 * 测试用例执行器
 * todo 打印LOG
 *
 * @author huangxiahao
 */
public class CaseActuator implements Actuator {

    private Long projectId;

    private Long envId;

    private CheckPointActuator checkPointActuator;

    private HttpClientActuator httpClientActuator;

    private final String baseJsPath = "syntaxCheck.js";

    public CaseActuator(Long envId, Long projectId)  {
        this.projectId = projectId;
        this.envId = envId;
        checkPointActuator = new CheckPointActuator(baseJsPath, envId, projectId);
        httpClientActuator = new HttpClientActuator(new HttpRequestConfig(), envId, projectId);
    }

    /**
     * 执行测试用例
     */
    public TestCaseExecuteResult executeTestCase(TestCase testCase) {
        //todo 李迪凡 执行前置动作
        //执行测试用例的本体内容
        BaseTestCaseResponseDetail baseTestCaseResponseDetail = null;
        if (testCase.getType().equals(TestCaseTypeEnum.HTTP.getValue())) {
            HttpRequestDetail httpRequestDetail = JSON.parseObject(testCase.getDetail(), HttpRequestDetail.class);
            baseTestCaseResponseDetail = httpClientActuator.sendHttpRequest(httpRequestDetail);
        }
        //todo 李迪凡 执行测试后动作
        //进行检验
         CheckPointResult checkPointResult = null;
        if (testCase.getType().equals(TestCaseTypeEnum.HTTP.getValue())) {
           checkPointResult = checkPointActuator.httpCheck((HttpResponseDetail) baseTestCaseResponseDetail, getCheckPointEntity(testCase));
        }
        //todo 李迪凡 执行后置动作
        return new TestCaseExecuteResult(baseTestCaseResponseDetail, checkPointResult);
    }

    private CheckPoint getCheckPointEntity(TestCase testCase) {
        CheckPoint checkPoint = new CheckPoint();
        if (testCase.getAbnormalCheckpoint()==0){
            checkPoint.setUseExceptionCheck(false);
        }else {
            checkPoint.setUseExceptionCheck(true);
        }
        if (testCase.getNoEmptyCheckpoint()==0){
            checkPoint.setUseNullCheck(false);
        }else {
            checkPoint.setUseNullCheck(true);
        }
        checkPoint.setContainCheckPoint(testCase.getContainCheckpoint());
        checkPoint.setNoContainCheckPoint(testCase.getNoContainCheckpoint());
        checkPoint.setJsonPathCheckPoint(testCase.getJsonpathCheckpoint());
        return checkPoint;
    }



}
