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;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

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

    private final CheckPointActuator checkPointActuator;

    private final HttpClientActuator httpClientActuator;

    private final String baseJsPath = "syntaxCheck.js";

    public CaseActuator(CheckPointActuator checkPointActuator, HttpClientActuator httpClientActuator) {
        this.checkPointActuator = checkPointActuator;
        this.httpClientActuator = httpClientActuator;
    }

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



}
