package net.educoder.ecsonar.task;

import com.alibaba.fastjson.JSONObject;
import net.educoder.ecsonar.constant.Constant;
import net.educoder.ecsonar.model.CloudTaskInfoDetail;
import net.educoder.ecsonar.model.SonarScannerParam;
import net.educoder.ecsonar.services.DbOperateService;
import net.educoder.ecsonar.services.SonarService;
import net.educoder.ecsonar.utils.SystemUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.util.concurrent.ExecutorService;

/**
 * @Author: youys
 * @Date: 2022/7/5
 * @Description: 云脑质量分析线程
 */
public class CloudBrainQualityInspectRunnable implements Runnable {

    private final Logger LOGGER = LoggerFactory.getLogger(CloudBrainQualityInspectRunnable.class);

    private CloudTaskInfoDetail cloudTaskInfoDetail;
    private SonarService sonarService;
    private DbOperateService dbOperateService;
    private ExecutorService queryResultPool;


    public CloudBrainQualityInspectRunnable(CloudTaskInfoDetail cloudTaskInfoDetail,
                                            SonarService sonarService,
                                            DbOperateService dbOperateService,
                                            ExecutorService queryResultPool) {
        this.cloudTaskInfoDetail = cloudTaskInfoDetail;
        this.sonarService = sonarService;
        this.dbOperateService = dbOperateService;
        this.queryResultPool = queryResultPool;
    }

    @Override
    public void run() {

        String projectName = cloudTaskInfoDetail.getProjectName();
        // 调用sonar服务
        LOGGER.info("projectName:{}, detailId:{} 开始调用sonar分析,语言:{}", projectName, cloudTaskInfoDetail.getId(), cloudTaskInfoDetail.getLanguage());

        // 需要先git clone 到某个目录下面
        String path = String.format("/tmp/%s", projectName);
        SystemUtil.ExecuteResp executeResp = gitClone(path, cloudTaskInfoDetail.getGitUrl());
        if (executeResp.getStatus() != 0) {
            LOGGER.warn("projectName:{} git clone失败", cloudTaskInfoDetail.getProjectName());
            return;
        }

        String projectKey = projectName;
        String projectPath = path;

        String language = cloudTaskInfoDetail.getLanguage();
        // c和c++需要额外做一些处理
        if (sonarService.supportLanguage(language)) {
            SonarScannerParam scannerParam = new SonarScannerParam(projectKey, projectPath);
            if (Constant.C.equalsIgnoreCase(language) || Constant.CPP.equalsIgnoreCase(language)) {
                String resultPath = String.format("/tmp/%s", cloudTaskInfoDetail.getTaskId());
                File f = new File(resultPath);
                if (!f.exists()) {
                    f.mkdirs();
                }
                scannerParam.setCppCheckReportPath(resultPath + String.format("/%s-result.xml", projectName));

            }
            sonarService.sonar(cloudTaskInfoDetail.getLanguage(), scannerParam);
        } else {
            sonarService.sonar(projectPath, projectKey);
        }

        CloudBrainQueryResultRunnable queryResultRunnable = new CloudBrainQueryResultRunnable(projectName, cloudTaskInfoDetail.getId(), dbOperateService);
        queryResultPool.execute(queryResultRunnable);
    }

    /**
     * 克隆代码
     *
     * @param path
     * @param gitUrl
     * @return
     */
    private SystemUtil.ExecuteResp gitClone(String path, String gitUrl) {

        String command = StringUtils.join("rm -rf ", path, " && mkdir -p ", path, " && cd ", path, " && git clone ", gitUrl);

        LOGGER.info("git clone：command:{}", command);
        SystemUtil.ExecuteResp executeResp = SystemUtil.executeAndGetExitStatus(command);

        LOGGER.info("git clone结果:{}", JSONObject.toJSONString(executeResp));
        return executeResp;
    }
}
