package com.bocloud.ims.service.config;

import java.net.URI;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.Map;

import org.apache.http.conn.ssl.SSLContextBuilder;
import org.apache.http.conn.ssl.TrustStrategy;
import org.apache.http.impl.client.HttpClientBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;

import com.bocloud.common.model.BocloudResult;
import com.offbytwo.jenkins.JenkinsServer;
import com.offbytwo.jenkins.client.JenkinsHttpClient;
import com.offbytwo.jenkins.model.Build;
import com.offbytwo.jenkins.model.BuildResult;
import com.offbytwo.jenkins.model.BuildWithDetails;
import com.offbytwo.jenkins.model.JobWithDetails;

/**
 * jenkins 配置
 * 
 * @author ymh
 * @时间 2019年11月19日
 */
@SuppressWarnings("deprecation")
@Configuration
public class JenkinsConfiguration {

	private static final Logger logger = LoggerFactory.getLogger(JenkinsConfiguration.class);

	@Value("${jenkins.username:admin}")
	private String username;
	@Value("${jenkins.password:IHwTcq1Eu4yv0EwvEIz3kQX7jpI32aNK}")
	private String password;
	@Value("${jenkins.url:https://10.4.8.80:8081}")
	private String jenkinsUrl;

	private static HttpClientBuilder builder;
	private static JenkinsServer instance;

	static {
		try {
			builder = HttpClientBuilder.create();
			builder.setSSLContext(new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
				@Override
				public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
					return true;
				}
			}).build());
		} catch (Exception e) {
			logger.error("jenkin认证异常:" + e.getMessage());
		}
	}

	public JenkinsServer jenkinsServer() throws Exception {
		if (null == instance) {
			logger.info("jenkins.url: " + this.jenkinsUrl + " == username : " + this.username);
			JenkinsHttpClient jenkinsHttpClient = new JenkinsHttpClient(new URI(this.jenkinsUrl), builder,
					this.username, this.password);
			instance = new JenkinsServer(jenkinsHttpClient);
		}
		return instance;
	}

	// create host deploy-openstack-compute
	// create ceph ceph-add-node
	// delete ceph ceph-remove-node
	public Integer createJob(String jobName) throws Exception {
		return createJob(jobName, null);
	}

	public Integer createJob(String jobName, Map<String, String> params) throws Exception {
		JobWithDetails jobWithDetails = jenkinsServer().getJob(jobName);
		int nextBuildNumber = jobWithDetails.getNextBuildNumber();
		if (null != params) {
			jobWithDetails.build(params, true);
		} else {
			jobWithDetails.build(true);
		}
		Thread.sleep(5000);
		return nextBuildNumber;
	}

	public BocloudResult createResult(int nextBuildNumber, String jobName) throws Exception {
		BocloudResult bocloudResult = new BocloudResult(false, "Jenkins任务失败！");
		try {
			Long startTime = System.currentTimeMillis();
			Thread.sleep(5000);
			Boolean flag = false;
			while (!flag) {
				Long endTime = System.currentTimeMillis();
				// 等待60s
				if (endTime - startTime > 60 * 1000 * 80) {
					flag = true;
					bocloudResult.setMessage("Jenkins任务超时！");
					break;
				}
				JobWithDetails jobWithDetails = jenkinsServer().getJob(jobName);
				Build build = jobWithDetails.getBuildByNumber(nextBuildNumber);
				if (null == build) {
					Thread.sleep(60000);
					continue;
				}
				BuildWithDetails details = build.details();
				if (null == details) {
					Thread.sleep(60000);
					continue;
				}
				if (details.isBuilding()) {
					Thread.sleep(60000);
					continue;
				} else {
					flag = true;
					if (BuildResult.FAILURE == details.getResult()) {
						// 获取控制台日志
						String log = details.getConsoleOutputText();
						bocloudResult = new BocloudResult(false, "任务失败" + resultMsg(log));
					} else {
						bocloudResult = new BocloudResult(true, "任务完成！");
					}
					break;
				}
			}
			return bocloudResult;
		} catch (Exception e) {
			logger.error("任务失败：" + e.getMessage());
			return new BocloudResult(false, "任务失败：" + e.getMessage());
		}
	}

	public String resultMsg(String log) {
		String substring = "任务失败！";
		try {
			if (null != log) {
				int startIndex = log.indexOf("error");
				if (startIndex <= 0) {
					startIndex = log.indexOf("ERROR");
				}
				int endIndex = log.indexOf("[Pipeline]", startIndex);
				if (endIndex <= 0) {
					endIndex = log.length() + 1;
				}
				substring = log.substring(startIndex, endIndex);
			}
		} catch (Exception e) {
			logger.error("获取任务错误信息异常：" + e.getMessage());
		}
		return substring;
	}

}
