package cn.reghao.autodop.dmaster.app.service;

import cn.reghao.jdkutil.result.ResultStatus;
import cn.reghao.autodop.common.util.ExceptionUtil;
import cn.reghao.autodop.dmaster.app.model.po.log.BuildLog;
import cn.reghao.autodop.dmaster.app.service.bd.AppIntegrate;
import cn.reghao.autodop.dmaster.app.service.bd.tools.repo.CommitInfo;

import java.time.LocalDateTime;
import java.util.function.Supplier;

/**
 * 更新 -> 编译 -> 打包 -> 构建流水线
 *
 * @author reghao
 * @date 2021-05-22 13:28:31
 */
public class BuildSupplier implements Supplier<BuildLog> {
    private AppIntegrate appIntegrate;
    private BuildLog buildLog;

    public BuildSupplier(AppIntegrate appIntegrate) {
        this.appIntegrate = appIntegrate;
        // 由于是异步构建，从 UserContext 中获取当前用户必须是在请求所在的线程
        this.buildLog = BuildLog.from(appIntegrate.app());
    }

    @Override
    public BuildLog get() {
        long start = System.currentTimeMillis();
        try {
            CommitInfo commitInfo = appIntegrate.update();
            buildLog.setCommitInfo(commitInfo);
            buildLog.getBuildTime().setUpdateTotalTime(System.currentTimeMillis()-start);

            start = System.currentTimeMillis();
            appIntegrate.compile();
            buildLog.getBuildTime().setCompileTotalTime(System.currentTimeMillis()-start);

            start = System.currentTimeMillis();
            String packagePath = appIntegrate.pack();
            buildLog.setPackagePath(packagePath);
            buildLog.getBuildTime().setPackTotalTime(System.currentTimeMillis()-start);
        } catch (Exception e) {
            buildException(buildLog, e);
            return buildLog;
        }

        buildLog.getResult().setCode(ResultStatus.SUCCESS.getCode());
        buildLog.getResult().setMsg(ResultStatus.SUCCESS.getMsg());
        buildLog.getBuildTime().setBuildTime(LocalDateTime.now());
        return buildLog;
    }

    private void buildException(BuildLog buildLog, Exception e) {
        buildLog.getResult().setCode(ResultStatus.FAIL.getCode());
        buildLog.getResult().setMsg(ExceptionUtil.errorMsg(e));
        buildLog.getBuildTime().setBuildTime(LocalDateTime.now());
    }
}
