package cn.reghao.autodop.dmaster.app.service.bd.tools.compiler;

import lombok.extern.slf4j.Slf4j;
import org.apache.maven.shared.invoker.*;

import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

/**
 * Maven 编译，打包
 *
 * @author reghao
 * @date 2019-10-12 23:55:01
 */
@Slf4j
public class MavenCompiler implements CodeCompiler {
    private final String dirname;
    // TODO 和 EnvType 关联
    private final String env;
    private final InvocationRequest request;
    private final Invoker invoker;
    private final List<String> compileLog;

    public MavenCompiler(String homePath, String env, String dirname) {
        System.setProperty("maven.home", homePath);
        this.env = env;
        this.request = new DefaultInvocationRequest();
        this.invoker = new DefaultInvoker();
        this.compileLog = new ArrayList<>();
        this.dirname = dirname;
    }

    @Override
    public void compile(String appId, String appCompileHome) throws Exception {
        String pomPath = appCompileHome + "/pom.xml";
        setInvocationRequest(appId, pomPath);
        InvocationResult result = invoker.execute(request);
        if (result.getExitCode() != 0) {
            StringBuilder sb = new StringBuilder();
            compileLog.forEach(line -> sb.append(line).append(System.lineSeparator()));
            throw new Exception(sb.toString());
        } else {
            log.info("构建成功");
        }
    }

    /**
     * mvn clean package -Dmaven.test.skip=true -am -Pdev -pl dmaster
     *
     * @param
     * @return
     * @date 2020-05-12 上午10:36
     */
    private void setInvocationRequest(String appId, String pomPath) {
        request.setPomFile(new File(pomPath));
        // mvn clean package -Dmaven.test.skip=true
        request.setGoals(Arrays.asList("clean", "package", "-Dmaven.test.skip=true"));
        // -am
        request.setAlsoMake(true);
        // -Penv
        request.setProfiles(Collections.singletonList(env));
        // -pl app
        request.setProjects(Collections.singletonList(appId));
        // 清空前一次构建的日志
        // TODO 多线程环境时编译日志会出现问题
        compileLog.clear();
        request.setOutputHandler(compileLog::add);
    }
}
