package twitch.instrumentorum

import jetbrains.buildServer.configs.kotlin.v2018_2.TeamCityDsl

@TeamCityDsl
class BuildGroup(val project: InstrumProject, var parallel: Boolean) {
    internal val builds = arrayListOf<InstrumBuild>()
    internal val finalBuilds: ArrayList<InstrumBuild>
        get() = if (parallel) builds else arrayListOf(builds.last())
    internal val rootProject = project.rootProject

    init {
        project.buildGroups.add(this)
    }

    constructor(parent: InstrumProject, parallel: Boolean = false, init: BuildGroup.() -> Unit) :
        this(parent, parallel) {
        init()
    }

    internal fun finalize() {
        builds.forEach { it.finalize() }
    }

    internal fun finalizeBuildChain(chainFrom: BuildGroup?) {
        val dependencies = arrayListOf<InstrumBuild>()

        if (chainFrom != null) {
            dependencies.addAll(chainFrom.finalBuilds)
        }

        builds.forEach { build ->
            build.finalizeBuildChain(dependencies)

            if (!parallel) {
                dependencies.clear()
                dependencies.add(build)
            }
        }
    }

    internal fun findBuild(buildName: String): InstrumBuild? =
        rootProject.findBuild(buildName, builds)

    internal fun findBuild(idNamespace: String, buildName: String): InstrumBuild? =
        rootProject.findBuild(idNamespace, buildName, builds)

    internal fun matchingBuilds(buildId: String): List<InstrumBuild> =
        builds.filter { it.id?.value?.endsWith(buildId, true) == true }

    fun build(buildName: String, init: InstrumBuild.() -> Unit): InstrumBuild =
        InstrumBuild(buildName, this, init)
}
