buildscript {
    rootProject.version = '0.16.0'
    rootProject.group = 'ch.tutteli.atrium'

    def toolProjectsFun = subprojects.findAll {
        it.projectDir.path.contains('/misc/tools/') || it.projectDir.path.contains('\\misc\\tools\\')
    }
    ext {
        // main
        kbox_version = '0.15.1'
        kbox = { "ch.tutteli.kbox:kbox:$kbox_version" }
        niokVersion = '1.4.1'
        niok = { "ch.tutteli.niok:niok:$niokVersion" }
        kotlin_version = '1.3.72'

        // test
        jacocoToolVersion = '0.8.6'
        junitPlatformVersion = '1.7.1'
        jupiterVersion = '5.7.1'
        spek2Version = '2.0.12'
        spekExtensionsVersion = '1.2.1'
        spekExtensions = { "ch.tutteli.spek:tutteli-spek-extensions:$spekExtensionsVersion" }
        mockkVersion = '1.10.0'

        //TODO remove with 1.0.0
        mockito_kotlin_version = '2.2.0'
        mockito = { "com.nhaarman.mockitokotlin2:mockito-kotlin:$mockito_kotlin_version" }

        // project setup
        tutteli_plugins_version = '0.33.1'
        node_plugin_version = '2.2.0'
        d8_version = '1.6.84'

        // gh-pages.gradle
        docProjects = (subprojects - toolProjectsFun).findAll {
            !it.name.endsWith("-js") &&
                !it.name.endsWith("-android") &&
                !it.name.contains("robstoll") &&
                it.name != "${rootProject.name}-spec" &&
                !it.name.startsWith("${rootProject.name}-specs")

        }
        findSamples = { Collection<Project> projects ->
            projects.findAll { it.name.contains("-api-") }
                .collect { Paths.get(it.projectDir.absolutePath + "/src/test/kotlin/ch/tutteli/atrium/api/") }
                .findAll { Files.exists(it) }
                .collect {
                    List<java.nio.file.Path> l = Files.walk(it, 10).withCloseable { stream ->
                        return stream
                            .filter { file -> file.fileName.toString().endsWith("Samples.kt") }
                            .collect(Collectors.toList())
                    }
                    l.collect { it.toAbsolutePath().toString() }
                }.flatten()
        }

        ghPages_version = rootProject.version
        srcKotlin = 'src/main/kotlin'
        github_url = "https://github.com/robstoll/${rootProject.name}"
        dokka_sourceMapping = "tree/v0.16.0"


        toolProjects = toolProjectsFun

        // jacoco-multi-project.gradle
        jacocoMulti = [
            sourceProjects:
                (subprojects - toolProjectsFun).findAll {
                    !it.name.endsWith("-js") &&
                        // would have two classes with the same name if we add it as project as well,
                        // (clashes with "${project.name}-translations-en_GB-jvm"
                        it.name != "${rootProject.name}-translations-de_CH-common" &&
                        it.name != "${rootProject.name}-translations-de_CH-jvm" &&
                        // does not make sense to listen specs in coverage
                        !it.name.startsWith("${rootProject.name}-specs") &&
                        !it.name.contains("smoke-test")

                },
            jacocoProjects:
                (subprojects - toolProjectsFun).findAll {
                    !(it.projectDir.path.contains("/translations/") || it.projectDir.path.contains("\\translations\\")) &&
                        !it.name.endsWith("-common") &&
                        !it.name.endsWith("-js") &&
                        it.name != "${rootProject.name}-domain-api-jvm" &&
                        it.name != "${rootProject.name}-core-robstoll-jvm" &&
                        !it.name.startsWith("${rootProject.name}-specs") &&
                        //TODO remove with 0.17.0
                        it.name != "${rootProject.name}-domain-robstoll-jvm" &&
                        it.name != "${rootProject.name}-domain-builders-jvm"
                }
        ]
    }

    repositories {
        mavenCentral()
        maven { url "https://plugins.gradle.org/m2/" }
    }
    dependencies {
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
        classpath "ch.tutteli:tutteli-gradle-dokka:$tutteli_plugins_version"
        classpath "ch.tutteli:tutteli-gradle-kotlin-module-info:$tutteli_plugins_version"
        classpath "ch.tutteli:tutteli-gradle-kotlin-utils:$tutteli_plugins_version"
        classpath "ch.tutteli:tutteli-gradle-project-utils:$tutteli_plugins_version"
        classpath "ch.tutteli:tutteli-gradle-publish:$tutteli_plugins_version"
        classpath "ch.tutteli:tutteli-gradle-spek:$tutteli_plugins_version"
        classpath "com.github.node-gradle:gradle-node-plugin:$node_plugin_version"
    }
}

apply plugin: "ch.tutteli.project.utils"
apply plugin: 'ch.tutteli.kotlin.utils'
kotlinutils.kotlinVersion = kotlin_version

repositories {
    mavenCentral()
    jcenter()
}

configurations {
    dependabot
}

dependencies {
    // helps dependabot to recognise versions which it should update
    dependabot "org.jacoco:org.jacoco.core:$jacocoToolVersion"
    dependabot "org.junit.jupiter:junit-jupiter-engine:$jupiterVersion"
    dependabot "org.junit.platform:junit-platform-console:$junitPlatformVersion"
    dependabot "ch.tutteli.spek:tutteli-spek-extensions:$spekExtensionsVersion"
    dependabot "ch.tutteli.niok:niok:$niokVersion"
    dependabot "ch.tutteli.kbox:kbox:$kbox_version"

    //TODO remove with 1.0.0
    dependabot "com.nhaarman.mockitokotlin2:mockito-kotlin:$mockito_kotlin_version"

}

subprojects {
    group = rootProject.group

    repositories {
        mavenCentral()
    }
}

def commonProjects = getCommonProjects()
def jsProjects = getJsProjects()
def jvmProjects = getJvmProjects()
def multiplatformProjects = commonProjects + jsProjects + jvmProjects

configureCommonProjects()
configureAndroidProjects()
configureJsProjects()
configureJvmProjects()

configure(subprojects.findAll {
    def parentName = it.projectDir.parentFile.name
    it.name != "bc-tests" && parentName != "old" && parentName != "bc-tests"
} - multiplatformProjects) {
    apply plugin: 'kotlin'
    dependencies {
        implementation kotlinStdlib()
    }
}

configure(commonProjects) {
    compileKotlinCommon {
        kotlinOptions.languageVersion = '1.2'
    }
    compileTestKotlinCommon {
        //TODO activate as soon as https://youtrack.jetbrains.com/issue/KT-30580 is fixed
        kotlinOptions.allWarningsAsErrors = false
    }
}
configure(jsProjects) { subProject ->
    compileKotlin2Js {
        kotlinOptions {
            if (subProject.name.startsWith("atrium-translations")) {
                //necessary as the module name is then also called atrium-translations-js and can be shared (the name) by the other translation modules
                outputFile = "$buildDir/classes/kotlin/main/atrium-translations-js.js"
            }
            languageVersion = '1.2'
        }
    }

    compileTestKotlin2Js {
        //TODO activate as soon as https://youtrack.jetbrains.com/issue/KT-21348 is fixed
        kotlinOptions.allWarningsAsErrors = false
    }
}

def nonCommonAndJsProjects = subprojects - commonProjects - jsProjects
configure(nonCommonAndJsProjects - toolProjects) { Project subproject ->
    apply plugin: 'ch.tutteli.dokka'
    apply plugin: 'ch.tutteli.kotlin.module.info'

    dokka {
        logging.setLevel(LogLevel.QUIET)
        samples = findSamples([subproject])
    }
    compileKotlin {
        kotlinOptions {
            languageVersion = '1.2'
            //TODO activate as soon as https://youtrack.jetbrains.com/issue/KT-34257 is fixed
            allWarningsAsErrors = false
        }
    }

    sourceCompatibility = 8
    targetCompatibility = 8
}

//allow kotlin 1.3 for kotlin_1_3 modules
configure(subprojects.findAll { it.name.endsWith('-kotlin_1_3-common') }) {
    compileKotlinCommon.kotlinOptions.languageVersion = '1.3'
}
configure(subprojects.findAll { it.name.endsWith('-kotlin_1_3-android') }) {
    compileKotlin.kotlinOptions.languageVersion = '1.3'
}
configure(subprojects.findAll { it.name.endsWith('-kotlin_1_3-js') }) {
    compileKotlin2Js.kotlinOptions.languageVersion = '1.3'
}
configure(subprojects.findAll { it.name.endsWith('-kotlin_1_3-jvm') }) {
    compileKotlin.kotlinOptions.languageVersion = '1.3'
}


def apiProjects = subprojects.findAll {
    it.name.startsWith("${rootProject.name}-api") &&
        (it.name.endsWith("-jvm") ||
            (it.name.endsWith("-common") && (it.name.contains("api-fluent-") || it.name.contains("api-infix-")))
        )
}
//testJar and testSourcesJar for bc-tests
configure(apiProjects) { apiProject ->
    createTestJarTask(apiProject)
    createTestSourcesJarTask(apiProject)
}

def bundleSmokeTests = subprojects.findAll { it.name.contains('-smoke-test') }

configure(subprojects - bundleSmokeTests - toolProjects) { subproject ->
    apply plugin: 'ch.tutteli.publish'

    tutteliPublish {
        resetLicenses 'EUPL-1.2'
    }
}

configure(jacocoMulti.jacocoProjects + getAndroidProjects()) {
    apply plugin: 'ch.tutteli.spek'
    spek.version = spek2Version

    dependencies {
        testImplementation mockito(), excludeKotlin
    }

    afterEvaluate {
        junitjacoco {

            jacoco {
                toolVersion = jacocoToolVersion
            }

            jacocoReport {
                if (project.hasProperty('jacoco_additional')) {
                    project.jacoco_additional.each { otherProject ->
                        sourceSets otherProject.sourceSets.main
                    }
                }
                reports {
                    html.enabled = true
                }
            }
        }
    }
}

configure(subprojects - toolProjects) {
    sourceSets {
        all {
            languageSettings {
                useExperimentalAnnotation('kotlin.Experimental')
            }
        }
    }
}


apply from: 'gradle/scripts/check-dexer.gradle'
apply from: 'gradle/scripts/gh-pages.gradle'
apply from: 'gradle/scripts/jacoco-multi-project.gradle'

configure(bundleSmokeTests) {

    def suffix = "-smoke-test"
    def isABundleAndNotExtensionSmokeTest = it.name.endsWith(suffix)
    if (isABundleAndNotExtensionSmokeTest) {
        def bundleUnderTest = it.name.substring(0, it.name.indexOf(suffix))
        Project bundle = project(":$bundleUnderTest-jvm")

        description = "Represents a JDK >= 9 smoke test for $bundleUnderTest"

        sourceCompatibility = JavaVersion.current()
        targetCompatibility = JavaVersion.current()

        ext.jacoco_additional = [bundle]

        sourceSets {
            // we are reusing the source from the bundle, so that we do not have to re-invent the spec
            test { kotlin { srcDirs += ["${bundle.projectDir}/src/test/kotlin"] } }
        }

        dependencies {
            //I don't see how to set up compileTestKotlin with --patch-module, so we have put the module-info.java directly in src/test/kotlin instead
            testImplementation bundle
        }
    }
}


import java.nio.file.Files
import java.nio.file.Paths
import java.util.function.Function
import java.util.stream.Collectors

def createRegisterJsServicesTask(String projectName, String packageName, Function<String, Boolean> filter) {
    Project project = prefixedProject(projectName)
    configure(project) {
        def registerJsServices = project.tasks.create(name: 'generateJsRegisterServices', group: 'build') {
            def jvm = "${getProjectNameWithoutSuffix(project)}-jvm"
            def servicesDir = project.file("../$jvm/src/main/resources/META-INF/services/")
            def services = project.file("$srcKotlin/${packageName.replace('.', '/')}/registerServices.kt")
            inputs.dir servicesDir
            outputs.file services

            doLast {
                services.write("""\
                @file:Suppress("DEPRECATION")

                package $packageName

                import ch.tutteli.atrium.core.polyfills.registerService

                @Suppress("unused" /* here in order that the code is executed when module is loaded */)
                private val register = run {
            """.stripIndent())
                def sortedMap = new TreeMap<String, String>()
                servicesDir.traverse {
                    if (it.isFile() && filter.apply(it.name)) {
                        sortedMap.put(it.name, it.withReader { it.readLine() })
                    }
                }
                sortedMap.each { entry ->
                    services.append("\n    registerService<")
                    services.append(entry.key)
                    services.append("> { ")
                    services.append(entry.value)
                    services.append("() }")
                }
                services.append("\n}\n")
            }
        }
        compileKotlin2Js.dependsOn registerJsServices
    }
}

//TODO remove with 0.17.0
createRegisterJsServicesTask('core-robstoll-js', 'ch.tutteli.atrium.core.robstoll') { true }
createRegisterJsServicesTask('domain-builders-js', 'ch.tutteli.atrium.domain.builders') { true }
createRegisterJsServicesTask('domain-robstoll-js', 'ch.tutteli.atrium.domain.robstoll') {
    !(it in [
        'ch.tutteli.atrium.domain.creating.BigDecimalAssertions',
        'ch.tutteli.atrium.domain.creating.OptionalAssertions',
        'ch.tutteli.atrium.domain.creating.PathAssertions',
        'ch.tutteli.atrium.domain.creating.LocalDateAssertions',
        'ch.tutteli.atrium.domain.creating.LocalDateTimeAssertions',
        'ch.tutteli.atrium.domain.creating.ZonedDateTimeAssertions',
        'ch.tutteli.atrium.domain.creating.ChronoLocalDateAssertions',
        'ch.tutteli.atrium.domain.creating.ChronoLocalDateTimeAssertions',
        'ch.tutteli.atrium.domain.creating.ChronoZonedDateTimeAssertions'
    ])
}

List<Project> projectNamesToProject(String[] names) {
    names.collect { projectName -> prefixedProject(projectName) }
}

def createJsTestTask(String... subprojectNames) {
    configure(projectNamesToProject(subprojectNames)) {
        apply plugin: 'com.github.node-gradle.node'

        compileTestKotlin2Js.configure {
            kotlinOptions.moduleKind = "commonjs"
            kotlinOptions.sourceMap = true
            kotlinOptions.sourceMapEmbedSources = "always"
        }

        task populateNodeModules(type: Copy, dependsOn: compileKotlin2Js) {
            from compileKotlin2Js.destinationDir

            prefixedProject('verbs-internal-js').afterEvaluate {
                // TODO 0.17.0 or 0.18.0, check if still required with the new Kotlin MPP plugin
                configurations.testRuntimeClasspath.allDependencies.withType(ProjectDependency).each {
                    dependsOn(it.dependencyProject.assemble)
                }

                configurations.testRuntimeClasspath.each {
                    from zipTree(it.absolutePath).matching { include '*.js', '*.js.map' }
                }
            }

            into "${buildDir}/node_modules"
        }

        def nodeModulesParentDir = file("$rootProject.projectDir/gradle/")
        node {
            download = true
            npmVersion = '6.4.1'
            workDir = file("$rootProject.projectDir/.gradle/nodejs")
            npmWorkDir = file("$rootProject.projectDir/.gradle/npm")
            nodeModulesDir = nodeModulesParentDir
        }

        task runMocha(type: NpxTask, dependsOn: [compileTestKotlin2Js, populateNodeModules]) {
            command = "mocha"
            args = [compileTestKotlin2Js.outputFile]
        }
        test.dependsOn runMocha
    }
}

createJsTestTask(
    'core-api-js',
    'core-robstoll-lib-js',
    'api-fluent-en_GB-js',
    'api-infix-en_GB-js',
    'fluent-en_GB-js'
)

def useJupiter(String... projectNames) {
    configure(projectNamesToProject(projectNames)) {
        dependencies {
            testRuntimeOnly "org.junit.jupiter:junit-jupiter-engine:$jupiterVersion"
        }
        test {
            options {
                includeEngines 'junit-jupiter'
            }
        }
    }
}

useJupiter(
    'core-api-jvm',
    'api-fluent-en_GB-jvm',
    'api-infix-en_GB-jvm',
)

def getSubprojectTasks(String name) {
    return subprojects.collect { it.tasks.findByName(name) }.findAll { it != null }
}

task publishForScala(description: 'fast publish to maven local for scala projects') {
    dependsOn getSubprojectTasks('publishToMavenLocal')
}

gradle.taskGraph.whenReady { graph ->
    if (graph.hasTask(':publishForScala')) {
        ['test', 'dokka', 'signTutteliPublication', 'validateBeforePublish', 'javadocJar', 'sourcesJar'].forEach {
            getSubprojectTasks(it).forEach { it.enabled = false }
        }
    }
}

/*
Release & deploy a commit
--------------------------------

1. update master:

Either use the following commands or the manual steps below

export ATRIUM_PREVIOUS_VERSION=0.16.0
export ATRIUM_VERSION=0.16.0
find ./ -name "*.md" | xargs perl -0777 -i \
   -pe "s@$ATRIUM_PREVIOUS_VERSION@$ATRIUM_VERSION@g;" \
   -pe "s@tree/master@tree/v$ATRIUM_VERSION@g;" \
   -pe "s@latest#/doc@$ATRIUM_VERSION/doc@g;"
perl -0777 -i \
  -pe "s@$ATRIUM_PREVIOUS_VERSION@$ATRIUM_VERSION@g;" \
  -pe "s@dokka_sourceMapping = \"tree/master\"@dokka_sourceMapping = \"tree/v$ATRIUM_VERSION\"@;" \
  -pe "s/rootProject.version = '$ATRIUM_VERSION-SNAPSHOT'/rootProject.version = '$ATRIUM_VERSION'/;" \
  ./build.gradle
perl -0777 -i \
  -pe 's/(<!-- for master -->\n)\n([\S\s]*?)(\n<!-- for a specific release -->\n)<!--\n([\S\s]*?)-->\n(\n# <img)/$1<!--\n$2-->$3\n$4\n$5/;' \
  -pe 's/(---\n❗ You are taking[^-]*?---)/<!$1>/;' \
  ./README.md
git commit -a -m "v$ATRIUM_VERSION"

check changes
git push

alternatively the manual steps:

    a) change rootProject.version in build.gradle to X.Y.Z
    b) search for old version in README.md and replace with new
    c) search for `tree/master` in all .md files and replace it with `tree/vX.Y.Z`
    d) adjust dokka_sourceMapping from `tree/master` to tree/vX.Y.Z
    e) search for `latest#/doc` in all .md files and replace with `X.Y.Z/doc`
    f) use the release badges in README (comment out the ones for master and uncomment the ones for the release)
    g) comment out the warning in README.md about taking a sneak peak
    h) commit & push (modified CONTRIBUTING.md, differences.md, build.gradle and README.md)

2. prepare release on github
    a) git tag vX.Y.Z
    b) git push origin vX.Y.Z
    c) Log in to github and create draft for the release

The tag is required for dokka in order that the source-mapping works

3. update github pages:
Assumes you have a atrium-gh-pages folder on the same level as atrium where the gh-pages branch is checked out

Either use the following commands or the manual steps below (assuming ATRIUM_VERSION is already set from commands above)

gr ghPages
perl -0777 -i \
  -pe "s@$ATRIUM_PREVIOUS_VERSION@$ATRIUM_VERSION@g;" \
  ../atrium-gh-pages/latest/index.html
perl -0777 -i \
  -pe "s@(- \[$ATRIUM_PREVIOUS_VERSION\]\($ATRIUM_PREVIOUS_VERSION\))@- \[$ATRIUM_VERSION\]\($ATRIUM_VERSION\)\n\$1@;" \
  ../atrium-gh-pages/README.md
cd ../atrium-gh-pages
git add . && git commit -m "v$ATRIUM_VERSION"

check changes
git push

cd ../atrium

alternatively the manual steps:
    a) gr ghPages
    b) change version number in atrium-gh-pages/latest/index.html
    c) add new version to atrium-gh-pages/README.md
    d) commit & push changes

3. deploy to bintray:
(assumes you have an alias named gr pointing to ./gradlew)
    a) java -version 2>&1 | grep "version \"9" && CI=true gr clean publishToBintray
    b) Log in to bintray, check that there are 960 artifacts and publish them
    c) synchronise to maven central

4. publish release on github
    1) Log in to github and publish draft

Prepare next dev cycle
-----------------------
    1. update master:

Either use the following commands or the manual steps below

export ATRIUM_VERSION=0.16.0
export ATRIUM_NEXT_VERSION=0.16.0
find ./ -name "*.md" | xargs perl -0777 -i \
   -pe "s@tree/v$ATRIUM_VERSION@tree/master@g;" \
   -pe "s@$ATRIUM_VERSION/doc@latest#/doc@g;" \
   -pe "s/add \\\`\@since $ATRIUM_VERSION\\\` \(adapt to current/add \\\`\@since $ATRIUM_NEXT_VERSION\\\` \(adapt to current/g;"
perl -0777 -i \
  -pe "s@dokka_sourceMapping = \"tree/v$ATRIUM_VERSION\"@dokka_sourceMapping = \"tree/master\"@;" \
  -pe "s/rootProject.version = '$ATRIUM_VERSION'/rootProject.version = '$ATRIUM_NEXT_VERSION-SNAPSHOT'/;" \
  -pe "s/ATRIUM_VERSION=$ATRIUM_VERSION/ATRIUM_VERSION=$ATRIUM_NEXT_VERSION/;" \
  ./build.gradle
perl -0777 -i \
  -pe 's/(<!-- for master -->\n)<!--\n([\S\s]*?)-->(\n<!-- for a specific release -->)\n([\S\s]*?)\n(\n# <img)/$1\n$2$3\n<!--$4-->\n$5/;' \
  -pe 's/<!(---\n❗ You are taking[^-]*?---)>/$1/;' \
  -pe "s@(For instance, the \[README of v$ATRIUM_VERSION\].*tree/)master/@\$1v$ATRIUM_VERSION/@;" \
  ./README.md
git commit -a -m "prepare dev cycle of $ATRIUM_NEXT_VERSION"

check changes
git push

alternatively the manual steps:

    a) search for `tree/vX.Y.Z` in all .md and build.gradle files and replace it with `tree/v0.12.0`
b) search for `X.Y.Z/doc` in all .md files and replace with `latest#/doc`
   c) use the master badges in README (uncomment them in README and comment out release badges)
   d) uncomment the warning about taking a sneak peek in README and revert `tree/v0.12.0` still point to the tag
e) change rootProject.version in build.gradle to X.Y.Z-SNAPSHOT
f) commit & push changes

2. establish backward compatibility tests for the previous version
a) add new version at the end of atrium-bc-test/build.gradle
b) git commit -a -m "establish backward compatibility tests for v$ATRIUM_VERSION"
c) commit & push changes

3. update samples (optional, since dependabot will create pull requests)
a) use newly released version in samples (search again for the old-version and replace with new)
b) commit & push changes

*/
