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

import cn.reghao.autodop.dmaster.app.db.query.config.CompilerConfigQuery;
import cn.reghao.autodop.dmaster.app.db.query.config.PackerConfigQuery;
import cn.reghao.autodop.dmaster.app.db.query.config.RepoAuthConfigQuery;
import cn.reghao.autodop.dmaster.app.model.po.config.build.CompilerConfig;
import cn.reghao.autodop.dmaster.app.model.po.config.build.PackerConfig;
import cn.reghao.autodop.dmaster.app.model.po.config.build.RepoAuthConfig;
import cn.reghao.autodop.dmaster.app.model.po.config.AppConfig;
import cn.reghao.autodop.dmaster.app.model.vo.BuildConfig;
import org.springframework.stereotype.Service;

/**
 * 检查并设置共享实体
 *
 * @author reghao
 * @date 2020-11-13 17:58:27
 */
@Service
public class SharedEntityChecker {
    private RepoAuthConfigQuery repoAuthConfigQuery;
    private CompilerConfigQuery compilerConfigQuery;
    private PackerConfigQuery packerConfigQuery;

    public SharedEntityChecker(RepoAuthConfigQuery repoAuthConfigQuery, CompilerConfigQuery compilerConfigQuery,
                               PackerConfigQuery packerConfigQuery) {
        this.repoAuthConfigQuery = repoAuthConfigQuery;
        this.compilerConfigQuery = compilerConfigQuery;
        this.packerConfigQuery = packerConfigQuery;
    }

    /**
     * 检查构建共享配置
     *
     * @param
     * @return
     * @date 2020-09-30 下午3:17
     */
    public void checkAndSetBuildConfig(AppConfig app) throws Exception {
        BuildConfig buildConfig =
                new BuildConfig(app.getRepoAuthConfig(), app.getCompilerConfig(), app.getPackerConfig());
        checkAndSetBuildConfig(buildConfig);
        app.setRepoAuthConfig(buildConfig.getRepoAuth());
        app.setCompilerConfig(buildConfig.getCompiler());
        app.setPackerConfig(buildConfig.getPacker());
    }

    public void checkAndSetBuildConfig(BuildConfig buildConfig) throws Exception {
        RepoAuthConfig repoAuth = buildConfig.getRepoAuth();
        RepoAuthConfig repoAuthConfig = repoAuthConfigQuery.findByName(repoAuth.getName());
        if (repoAuthConfig != null) {
            buildConfig.setRepoAuth(repoAuthConfig);
        } else {
            throw new Exception("仓库配置 " + repoAuth.getName() + " 不存在");
        }

        CompilerConfig compiler = buildConfig.getCompiler();
        CompilerConfig compilerConfig = compilerConfigQuery.findByName(compiler.getName());
        if (compilerConfig != null) {
            buildConfig.setCompiler(compilerConfig);
        } else {
            throw new Exception("编译器配置 " + compiler.getName() + " 不存在");
        }

        PackerConfig packer = buildConfig.getPacker();
        PackerConfig packerConfig = packerConfigQuery.findByName(packer.getName());
        if (packerConfig != null) {
            buildConfig.setPacker(packerConfig);
        } else {
            throw new Exception("打包配置 " + packer.getName() + " 不存在");
        }
    }
}
