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.CompilerDto;
import cn.reghao.bnt.web.devops.builder.model.LocalBuildDir;
import cn.reghao.bnt.web.devops.builder.model.constant.CompileType;
import cn.reghao.bnt.web.devops.builder.tool.compiler.CodeCompiler;
import lombok.extern.slf4j.Slf4j;

import java.io.File;

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

        CodeCompiler codeCompiler = BuildTools.getCodeCompiler(appId);
        String appCompileDir = LocalBuildDir.compileDir + File.separator + appId;
        String compileDir = appCompileDir + File.separator + appDto.getProjDirname();
        long start = System.currentTimeMillis();
        CompilerDto compilerDto = appDto.getBuildConfigDto().getCompilerDto();
        String compileType = compilerDto.getType();
        if (compileType.equals(CompileType.maven.getName())) {
            codeCompiler.compile(appId, compileDir, appDto.getEnv(), appDto.getAppRootPath());
        } else if (compileType.equals(CompileType.shell.getName())) {
            codeCompiler.compile(appId, compileDir);
        } else if (compileType.equals(CompileType.docker.getName())) {
            codeCompiler.compile(appId, compileDir);
        } else if (compileType.equals(CompileType.none.getName())) {

        } else {
            String errMsg = String.format("unknown compile type %s with app %s", compileType, appId);
            throw new Exception(errMsg);
        }

        buildResult.getBuildConsumedDto().setCompileConsumed(System.currentTimeMillis()-start);
        if (next != null) {
            next.handle(buildParam, buildResult);
        }
    }
}
