package cn.reghao.bnt.web.devops.builder.chain.impl;

import cn.reghao.bnt.web.devops.builder.chain.BuildTools;
import cn.reghao.bnt.web.devops.builder.chain.Handler;
import cn.reghao.bnt.web.devops.builder.model.AppDto;
import cn.reghao.bnt.web.devops.builder.model.LocalBuildDir;
import cn.reghao.bnt.web.devops.builder.tool.BuilderUtil;
import cn.reghao.bnt.web.devops.builder.tool.repo.CodeUpdater;
import cn.reghao.bnt.web.devops.builder.tool.repo.CommitInfo;
import lombok.extern.slf4j.Slf4j;

import java.io.File;

/**
 * @author reghao
 * @date 2022-05-06 16:02:38
 */
@Slf4j
public class UpdateHandler extends Handler<BuildChainParam, BuildChainResult> {
    @Override
    public void handle(final BuildChainParam buildParam, BuildChainResult buildResult) throws Exception {
        AppDto appDto = buildParam.getAppDto();
        String appId = appDto.getAppId();
        log.info("更新 {} 代码...", appId);

        CodeUpdater codeUpdater = BuildTools.getCodeUpdater(appId);
        long start = System.currentTimeMillis();
        CommitInfo commitInfo = update(appDto, codeUpdater);
        buildResult.getBuildConsumedDto().setPullConsumed(System.currentTimeMillis()-start);
        buildResult.setCommitInfo(commitInfo);

        if (next != null) {
            next.handle(buildParam, buildResult);
        }
    }

    public CommitInfo update(AppDto appDto, CodeUpdater codeUpdater) throws Exception {
        String remote;
        String branch;
        String local = LocalBuildDir.localRepo + File.separator + appDto.getAppId();
        remote = appDto.getAppRepo();
        branch = appDto.getRepoBranch();
        CommitInfo last = codeUpdater.latestCommitInfo(local, branch);
        CommitInfo current = codeUpdater.pull(remote, branch, local);
        if (last == null || last.getMsCommitTime() <= current.getMsCommitTime()) {
            // 本地仓库不存在 or 本地仓库版本和远程仓库相同 or 本地仓库版本落后于远程仓库
            BuilderUtil.copyToCompileDir(local, appDto);
        } else if (last.getMsCommitTime() > current.getMsCommitTime()) {
            throw new Exception("本地仓库代码比远程仓库更新");
        }

        return current;
    }
}
