// TODO: remove
/**
 * File generated by $ ./gradlew refreshVersions
 *
 * Gradle has replaced the buildscript { ... } block by a better alternative that looks like this
 *
```
plugins {
id("com.android.application")
id("com.louiscad.splitties")
id("org.jetbrains.kotlin.android")
id("org.jetbrains.kotlin.kapt")
id("kotlin-android-extensions")
}
```
 * This boilerplate does two things:
 *
 * 1. it configures the plugin versions using the file `versions.properties` generated by
 *     $ ./gradlew refreshVersions
 *
 * 2. it fixes the bug of the Android Gradle Plugin that doesn't publish the required metadata
 * Please see and upvote the issue:
 *     https://issuetracker.google.com/issues/64551265
 *
 * Include this file like this:
 *

```kotlin
// settings.gradle.kts
pluginManagement {
repositories {
google()
gradlePluginPortal()
}
}
apply(from = "plugins.gradle.kts")
// rootProject.name = xxx
// include(":app")
```

 ***/
@Suppress("CAST_NEVER_SUCCEEDS")
(this as Settings).pluginManagement {

    /**
     * This `resolutionStrategy` allows plugin versions to be configured from
     *     `versions.properties
     * The convention is simply
     *     plugin.$PLUGINID=$PLUGIN_VERSION
     * To check what happen, you can set the property
     *     resolutionStrategyConfig=verbose
     **/
    val versionProperties = file("../versions.properties")
    val resolutionStrategyConfig = extra["resolutionStrategyConfig"]
    if (resolutionStrategyConfig == "false" || versionProperties.canRead().not()) return@pluginManagement
    val androidPluginIds = listOf("com.android.application", "com.android.library")
    val kotlinPluginIds = listOf("org.jetbrains.kotlin.android", "org.jetbrains.kotlin.kapt", "kotlin-android-extensions")
    @Suppress("UNCHECKED_CAST")
    val properties: Map<String, String> = java.util.Properties().apply {
        load(versionProperties.reader())
    } as Map<String, String>
    resolutionStrategy.eachPlugin {
        val pluginId = requested.id.id
        val version = properties["plugin.$pluginId"]
        val message = when {
            pluginId in kotlinPluginIds -> {
                val module = "org.jetbrains.kotlin:kotlin-gradle-plugin:${properties["module.kotlin"]}"
                useModule(module)
                "ResolutionStrategy used module=$module for plugin=$pluginId"
            }
            pluginId in androidPluginIds -> {
                val module = "com.android.tools.build:gradle:${properties["module.android"]}"
                useModule(module)
                "ResolutionStrategy used module=$module for plugin=$pluginId"
            }
            version != null -> {
                useVersion(version)
                "ResolutionStrategy used version=$version for plugin=$pluginId"
            }
            else -> "ResolutionStrategy did not find a version for $pluginId"
        }
        if (resolutionStrategyConfig == "verbose") println(message)
    }
}
