package cn.reghao.bnt.web.devops.build.service;

import cn.reghao.bnt.web.devops.build.db.repository.CompilerConfigRepository;
import cn.reghao.bnt.web.devops.build.db.repository.PackerConfigRepository;
import cn.reghao.bnt.web.devops.build.db.repository.RepoAuthConfigRepository;
import cn.reghao.bnt.web.devops.build.model.po.CompilerConfig;
import cn.reghao.bnt.web.devops.build.model.po.PackerConfig;
import cn.reghao.bnt.web.devops.build.model.po.RepoAuthConfig;
import cn.reghao.bnt.web.devops.build.model.vo.BuildConfig;
import org.springframework.stereotype.Service;

/**
 * 检查并设置构建配置
 *
 * @author reghao
 * @date 2020-11-13 17:58:27
 */
@Service
public class BuildConfigChecker {
    private final RepoAuthConfigRepository repoAuthConfigRepository;
    private final CompilerConfigRepository compilerConfigRepository;
    private final PackerConfigRepository packerConfigRepository;

    public BuildConfigChecker(RepoAuthConfigRepository repoAuthConfigRepository,
                              CompilerConfigRepository compilerConfigRepository,
                              PackerConfigRepository packerConfigRepository) {
        this.repoAuthConfigRepository = repoAuthConfigRepository;
        this.compilerConfigRepository = compilerConfigRepository;
        this.packerConfigRepository = packerConfigRepository;
    }

    public BuildConfig checkAndGet(String repoAuthName, String compilerName, String packerName) throws Exception {
        RepoAuthConfig repoAuthConfig = repoAuthConfigRepository.findByName(repoAuthName);
        if (repoAuthConfig == null) {
            throw new Exception("仓库配置 " + repoAuthName + " 不存在");
        }

        CompilerConfig compilerConfig = compilerConfigRepository.findByName(compilerName);
        if (compilerConfig == null) {
            throw new Exception("编译器配置 " + compilerName + " 不存在");
        }

        PackerConfig packerConfig = packerConfigRepository.findByName(packerName);
        if (packerConfig == null) {
            throw new Exception("打包配置 " + packerName + " 不存在");
        }

        return new BuildConfig(repoAuthConfig, compilerConfig, packerConfig);
    }
}
