import com.android.build.gradle.AppPlugin
import com.android.build.gradle.LibraryPlugin
import dependencies.Dep
import dependencies.Packages
import publish.DistributionTrack
import publish.EditStatus
import publish.PromoteApk
import publish.UploadApk

apply from: file('gradle/dependencyGraph.gradle')

buildscript {
    ext {
        isCi = System.getenv("CI") == "true"
        isReleaseBuild = System.getenv("RELEASE_BUILD") == "true"
    }
    repositories {
        google()
        if (!isCi) {
            maven {
                url "https://maven-central-asia.storage-download.googleapis.com/repos/central/data/"
            }
        }
        jcenter()
        maven { url "https://kotlin.bintray.com/kotlinx" }
        maven { url 'https://dl.bintray.com/kotlin/kotlin-eap' }
        maven { url "https://dl.bintray.com/kotlin/ktor" }
        maven { url "http://kotlin.bintray.com/kotlin-dev" }
        maven { url "https://plugins.gradle.org/m2/" }
        maven { url 'https://maven.fabric.io/public' }
        maven { url "http://storage.googleapis.com/r8-releases/raw/master" }
    }
    dependencies {
        classpath Dep.GradlePlugin.android
        classpath Dep.GradlePlugin.kotlin
        classpath Dep.GradlePlugin.kotlinSerialization
        classpath Dep.GradlePlugin.playServices
        classpath Dep.GradlePlugin.safeArgs
        classpath Dep.GradlePlugin.jetifier
        classpath Dep.GradlePlugin.licensesPlugin
        classpath Dep.GradlePlugin.crashlytics
        classpath Dep.GradlePlugin.iconRibbonPlugin
    }
}

allprojects {
    repositories {
        google().content{
            // Workaround for https://youtrack.jetbrains.com/issue/KT-28128
            excludeGroup("Kotlin/Native")
        }
        if (!isCi) {
            maven {
                url "https://maven-central-asia.storage-download.googleapis.com/repos/central/data/"
                content {
                    excludeGroup("Kotlin/Native")
                }
            }
        }
        jcenter() {
            content {
                excludeGroup("Kotlin/Native")
            }
        }
        maven {
            url "https://kotlin.bintray.com/kotlinx"
            content {
                excludeGroup("Kotlin/Native")
            }
        }
        maven {
            url 'https://dl.bintray.com/kotlin/kotlin-eap'
            content {
                excludeGroup("Kotlin/Native")
            }
        }
        maven {
            url "http://kotlin.bintray.com/kotlin-dev"
            content {
                excludeGroup("Kotlin/Native")
            }
        }
        maven {
            url "https://dl.bintray.com/kotlin/ktor"
            content {
                excludeGroup("Kotlin/Native")
            }
        }
        maven {
            url "https://dl.bintray.com/soywiz/soywiz"
            content {
                excludeGroup("Kotlin/Native")
            }
        }
        maven {
            url 'https://oss.sonatype.org/content/repositories/snapshots/'
            content {
                excludeGroup("Kotlin/Native")
            }
        }
        maven {
            url "https://jitpack.io"
            content {
                excludeGroup("Kotlin/Native")
            }
        }
    }
    tasks.matching { it instanceof Test }.all {
        testLogging {
            events = ["failed", "skipped"]
            outputs.upToDateWhen { false }
            showStandardStreams = true
        }
    }
    plugins.whenPluginAdded {
        if (it instanceof AppPlugin || it instanceof LibraryPlugin) {
            project.with {
                configurations {
                    ktlint
                }

                dependencies {
                    ktlint "com.github.shyiko:ktlint:0.29.0"
                }

                task ktlint(type: JavaExec, group: "verification") {
                    def parameters = ["--android", '--editorconfig', "${rootProject.projectDir}/.editorconfig", "--reporter=checkstyle,output=${buildDir}/ktlint/checkstyle.xml"]

                    if (!isCi) {
                        parameters += "--reporter=html,artifact=me.cassiano:ktlint-html-reporter:0.2.0,output=${buildDir}/ktlint/checkstyle.html"
                    }

                    parameters += ['src/main/**/*.kt', 'src/debug/**/*.kt', 'src/release/**/*.kt', 'src/commonMain/**/*.kt', 'src/test/**/*.kt']

                    description = 'Check Kotlin code style.'
                    args = parameters
                    // https://github.com/shyiko/ktlint/blob/5fe8d0e203275a1a3337dc9777b50ec2a34a58df/ktlint/src/main/kotlin/com/github/shyiko/ktlint/Main.kt
                    main = 'com.github.shyiko.ktlint.Main'
                    classpath = configurations.ktlint
                }

                task ktlintFormat(type: JavaExec, group: "formatting") {
                    description = "Format Kotlin files based on code style."
                    classpath = configurations.ktlint
                    main = "com.github.shyiko.ktlint.Main"
                    args "--android", '-F', 'src/main/**/*.kt', 'src/debug/**/*.kt', 'src/release/**/*.kt', 'src/commonMain/**/*.kt', 'src/androidMain/**/*.kt', 'src/iOSMain/**/*.kt', 'src/test/**/*.kt'
                }

                task androidDependenciesExtra(dependsOn: 'androidDependencies') {
                    description 'Download extra dependencies for the CI Gradle Cache'
                    doLast {
                        // androidDependencies do not touch some configurations
                        configurations.findAll {
                            it.name.matches(/(ktlint|kapt|_internal_aapt2_binary|lintClassPath)/) && it.canBeResolved
                        }.files
                    }
                }
            }
        }
    }

    configurations.all {
        resolutionStrategy {
            eachDependency { DependencyResolveDetails details ->
                if (details.requested.group == 'com.android.tools.build.jetifier') {
                    details.useVersion '1.0.0-beta02'
                }
            }
        }
    }
    gradle.projectsEvaluated {
        tasks.withType(JavaCompile) {
            options.compilerArgs << "-Xmaxerrs" << "300"
        }
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

task dependencyReport {
    doLast {
        def file = new File("project-dependencies.dot")
        file.delete()
        file << "digraph {\n"
        file << "splines=ortho\n"
        rootProject.childProjects.each { item ->
            def from = item.value
            from.configurations.compile.dependencies
                    .matching { it in ProjectDependency }
                    .each { to -> file << ("\"${from.name}\" -> \"${to.name}\"\n") }
        }
        file << "}\n"
    }
}

task publishAlpha {
    doLast {
        def uploadApk = new UploadApk(logger)

        def apkFile = new File(System.getenv("UNIVERSAL_APK_PATH"))
        // FIXME more flexible
        def mappingFile = new File(rootProject.projectDir, ".transart/mapping.txt")

        uploadApk.execute(
                Packages.name,
                rootProject.file(".release/service-account.json"),
                apkFile,
                mappingFile,
                DistributionTrack.Alpha.INSTANCE,
                "New Alpha Release",
                EditStatus.Completed.INSTANCE,
                [
                        "en-US": rootProject.file("publish/release-notes/en-US/default.txt"),
                        "ja-JP": rootProject.file("publish/release-notes/ja-JP/default.txt")
                ]
        )
    }
}

task promoteProduction {
    doLast {
        def promoteApk = new PromoteApk(logger)
        def editId = project.property("editId")

        if (!editId) {
            throw new GradleScriptException("editId must be privided")
        }

        promoteApk.execute(
                Packages.name,
                rootProject.file(".release/service-account.json"),
                editId
        )
    }
}
