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.packer.CodePacker;
import lombok.extern.slf4j.Slf4j;

import java.io.File;

/**
 * @author reghao
 * @date 2022-05-06 16:02:50
 */
@Slf4j
public class PackHandler 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);

        String commitId = buildResult.getCommitInfo().getCommitId();
        CodePacker codePacker = BuildTools.getCodePacker(appId);
        String appCompileDir = LocalBuildDir.compileDir + File.separator + appId;
        String compileDir = appCompileDir + File.separator + appDto.getProjDirname();
        String appRootPath = compileDir + File.separator + appDto.getAppRootPath();
        String dockerfile = appDto.getDockerfile();

        long start = System.currentTimeMillis();
        String localPath = codePacker.pack(appId, commitId, appRootPath, dockerfile);
        buildResult.getBuildConsumedDto().setPackConsumed(System.currentTimeMillis()-start);

        log.info("推送已构建的 {} 应用...", appId);
        start = System.currentTimeMillis();
        String packagePath = codePacker.push(localPath);
        buildResult.setPackagePath(packagePath);
        buildResult.getBuildConsumedDto().setPushConsumed(System.currentTimeMillis()-start);

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