package util

import builders.JobBuilder
import javaposse.jobdsl.dsl.DslFactory
import org.yaml.snakeyaml.Yaml

class BuildUtils {

    public static DslFactory JOB_BASE
    private static Map configs
    public static String FOLDER = "directci"
    public static String DEFAULT_BUILDER_CLASS = 'DefaultBuilder'
    public static String DEFAULT_VERSION = '1.0-SNAPSHOT'
    public static String DEFAULT_EMAIL = 'direct-autotests-notifications@yandex-team.ru'


    static List<String> parseReposList(String reposListFile) {
        def dirs = []
        def reposFile = new File(reposListFile)
        reposFile.eachLine { dirs.add(it.replaceAll("/", "")) }
        return dirs.sort { it }
    }

    static Closure buildJob(Map config) {
        config = prepareConfig(config)
        getJobBuilder(config).build(config)
    }

    static Map initConfig(DslFactory jobBase) {
        JOB_BASE = jobBase;
        InputStream configFile = jobBase.streamFileFromWorkspace("$FOLDER/config.yml")
        Yaml configFileYml = new Yaml()
        configs = (Map) configFileYml.load(configFile)
        configs
    }

    static Map getConfig(String repoName) {
        def res = configs.get(repoName)
        res = res ?: new HashMap()
        res.repo = res.repo ?: Constants.SVN_LOCATION + "/${repoName}"
        res.repoName = repoName
        res as Map
    }

    private static Map prepareConfig(Map config) {
        config.version = config.version ?: DEFAULT_VERSION
        config.builderClass = config.builderClass ?: DEFAULT_BUILDER_CLASS
        config.email = config.email ?: DEFAULT_EMAIL
        config
    }

    private static JobBuilder getJobBuilder(Map config) {
        def gcl = new GroovyClassLoader(JOB_BASE.getClass().getClassLoader())
        def clazz = gcl.parseClass(JOB_BASE.readFileFromWorkspace("$FOLDER/builders/" + config.builderClass + ".groovy"))
        return clazz.newInstance()
    }
}
