package cn.qg.qaplatform.stools.controller;

import cn.qg.qaplatform.stools.utils.JenkinsApi;
import cn.qg.qaplatform.stools.vo.JenkinsBuildInfo;
import cn.qg.qaplatform.utils.JsonResult;
import com.offbytwo.jenkins.model.Build;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@CrossOrigin
@RestController
@RequestMapping("/jenkins")
public class JenkinsBuildController {

    /**
     * 获取构建信息列表
     * @param jobName 任务名称
     * @param num 获取的数量
     * @param project 项目名，非必填
     * @return 构建信息列表
     * @throws IOException
     */
    @GetMapping("/buildlist")
    public JsonResult getLatestBuildInfo(@RequestParam String jobName,
                                         @RequestParam Integer num,
                                         @RequestParam(required = false) String project) throws IOException {
        JenkinsApi jenkinsApi = new JenkinsApi();
        List<Build> buildList;
        if (project == null) {
            buildList = jenkinsApi.getJobBuildList(jobName, num);
        } else {
            buildList = jenkinsApi.getJobBuildList(jobName, num, project);
        }
        List<JenkinsBuildInfo> jenkinsBuildInfoList = new ArrayList<>();
        for (Build build: buildList) {
            JenkinsBuildInfo jenkinsBuildInfo = new JenkinsBuildInfo();
            jenkinsBuildInfo.setProject(build.details().getParameters().get("GIT_REPO"));
            jenkinsBuildInfo.setBranch(build.details().getParameters().get("BRANCH_NAME"));
            jenkinsBuildInfo.setNamespace(build.details().getParameters().get("NAMESPACE"));
            jenkinsBuildInfo.setUserName(build.details().getCauses().get(0).getUserName());
            jenkinsBuildInfo.setResult(build.details().getResult().toString());
            jenkinsBuildInfo.setCreateAt(new Date(build.details().getTimestamp()));
            jenkinsBuildInfoList.add(jenkinsBuildInfo);
        }
        return JsonResult.success(jenkinsBuildInfoList);
    }

    /**
     * 获取job列表
     * @return
     */
    @GetMapping("/joblist")
    public JsonResult getJenkinsJobList() {
        JenkinsApi jenkinsApi = new JenkinsApi();
        return JsonResult.success(jenkinsApi.getJobList());
    }
}
