apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-kapt'
apply plugin: 'kotlin-allopen'
apply plugin: 'com.google.gms.google-services'
apply plugin: 'com.hiya.jacoco-android'
apply plugin: 'com.google.firebase.crashlytics'

apply from: "${project.rootDir}/gradle/android_dependencies.gradle"
apply from: "${project.rootDir}/gradle/jacoco_global.gradle"

repositories {
    mavenCentral()
    google()
}

allOpen {
    // allows mocking for classes w/o directly opening them for release builds
    annotation 'info.nightscout.androidaps.annotations.OpenForTesting'
}

def generateGitBuild = { ->
    StringBuilder stringBuilder = new StringBuilder()
    try {
        def stdout = new ByteArrayOutputStream()
        exec {
            commandLine 'git', 'describe', '--always'
            standardOutput = stdout
        }
        String commitObject = stdout.toString().trim()
        stringBuilder.append(commitObject)
    } catch (ignored) {
        stringBuilder.append('NoGitSystemAvailable')
    }
    return stringBuilder.toString()
}

def generateGitRemote = { ->
    StringBuilder stringBuilder = new StringBuilder()
    try {
        def stdout = new ByteArrayOutputStream()
        exec {
            commandLine 'git', 'remote', 'get-url', 'origin'
            standardOutput = stdout
        }
        String commitObject = stdout.toString().trim()
        stringBuilder.append(commitObject)
    } catch (ignored) {
        stringBuilder.append('NoGitSystemAvailable')
    }
    return stringBuilder.toString()
}

def generateDate = { ->
    StringBuilder stringBuilder = new StringBuilder()
    stringBuilder.append((new Date()).format('yyyy.MM.dd-HH:mm'))
    return stringBuilder.toString()
}

def isMaster = { ->
    return !version.contains('-')
}

def gitAvailable = { ->
    StringBuilder stringBuilder = new StringBuilder()
    try {
        def stdout = new ByteArrayOutputStream()
        exec {
            commandLine 'git', '--version'
            standardOutput = stdout
        }
        String commitObject = stdout.toString().trim()
        stringBuilder.append(commitObject)
    } catch (ignored) {
        return false // NoGitSystemAvailable
    }
    return !stringBuilder.toString().isEmpty()

}

def allCommitted = { ->
    StringBuilder stringBuilder = new StringBuilder()
    try {
        def stdout = new ByteArrayOutputStream()
        exec {
            commandLine 'git', 'status', '-s'
            standardOutput = stdout
        }
        // ignore all changes done in .idea/codeStyles
        String cleanedList = stdout.toString().replaceAll(/(?m)^\s*(M|A|D|\?\?)\s*.*?\.idea\/codeStyles\/.*?\s*$/, "")
        // ignore all files added to project dir but not staged/known to GIT
        cleanedList = cleanedList.replaceAll(/(?m)^\s*(\?\?)\s*.*?\s*$/, "")
        stringBuilder.append(cleanedList.trim())
    } catch (ignored) {
        return false // NoGitSystemAvailable
    }
    return stringBuilder.toString().isEmpty()
}

tasks.matching { it instanceof Test }.all {
    testLogging.events = ["failed", "skipped", "started"]
    // testLogging.events = ["failed", "skipped", "started", "standard_out"] use to display stdout in travis
    testLogging.exceptionFormat = "full"
}

android {
    ndkVersion "21.1.6352462"

    defaultConfig {
        multiDexEnabled true
        versionCode 1500
        version "3.0.0.2-dev-j"
        buildConfigField "String", "VERSION", '"' + version + '"'
        buildConfigField "String", "BUILDVERSION", '"' + generateGitBuild() + '-' + generateDate() + '"'
        buildConfigField "String", "REMOTE", '"' + generateGitRemote() + '"'
        buildConfigField "String", "HEAD", '"' + generateGitBuild() + '"'
        buildConfigField "String", "COMMITTED", '"' + allCommitted() + '"'

    }

    flavorDimensions "standard"
    productFlavors {
        full {
            applicationId "info.nightscout.androidaps"
            dimension "standard"
            resValue "string", "app_name", "AndroidAPS"
            versionName version
            manifestPlaceholders = [
                    appIcon     : "@mipmap/ic_launcher",
                    appIconRound: "@mipmap/ic_launcher_round"
            ]
        }
        pumpcontrol {
            applicationId "info.nightscout.aapspumpcontrol"
            dimension "standard"
            resValue "string", "app_name", "Pumpcontrol"
            versionName version + "-pumpcontrol"
            manifestPlaceholders = [
                    appIcon     : "@mipmap/ic_pumpcontrol",
                    appIconRound: "@null"
            ]
        }
        nsclient {
            applicationId "info.nightscout.nsclient"
            dimension "standard"
            resValue "string", "app_name", "NSClient"
            versionName version + "-nsclient"
            manifestPlaceholders = [
                    appIcon     : "@mipmap/ic_yellowowl",
                    appIconRound: "@null"
            ]
        }
        nsclient2 {
            applicationId "info.nightscout.nsclient2"
            dimension "standard"
            resValue "string", "app_name", "NSClient2"
            versionName version + "-nsclient"
            manifestPlaceholders = [
                    appIcon     : "@mipmap/ic_yellowowl",
                    appIconRound: "@null"
            ]
        }
    }

    useLibrary "org.apache.http.legacy"
}

allprojects {
    repositories {
    }
}

dependencies {
    wearApp project(':wear')

    implementation project(':shared')
    implementation project(':core')
    implementation project(':automation')
    implementation project(':combo')
    implementation project(':database')
    implementation project(':dana')
    implementation project(':danars')
    implementation project(':danar')
    implementation project(':insight')
    implementation project(':pump-common')
    implementation project(':rileylink')
    implementation project(':medtronic')
    implementation project(':omnipod-common')
    implementation project(':omnipod-eros')
    implementation project(':omnipod-dash')
    implementation project(':diaconn')
    implementation project(':openhumans')

    implementation fileTree(include: ['*.jar'], dir: 'libs')

    /* Dagger2 - We are going to use dagger.android which includes
     * support for Activity and fragment injection so we need to include
     * the following dependencies */
    annotationProcessor "com.google.dagger:dagger-compiler:$dagger_version"
    annotationProcessor "com.google.dagger:dagger-android-processor:$dagger_version"
    kapt "com.google.dagger:dagger-android-processor:$dagger_version"

    /* Dagger2 - default dependency */
    kapt "com.google.dagger:dagger-compiler:$dagger_version"
}

apply from: "${project.rootDir}/gradle/test_dependencies.gradle"


/*
// Run 'adb' shell command to clear application data of main app for 'debug' variant
task clearMainAppData(type: Exec) {
    // we have to iterate to find the 'debug' variant to obtain a variant reference
    android.applicationVariants.all { variant ->
        if (variant.name == "fullDebug") {
            def applicationId = [variant.mergedFlavor.applicationId, variant.buildType.applicationIdSuffix].findAll().join()
            def clearDataCommand = ['adb', 'shell', 'pm', 'clear', applicationId]
            println "Clearing application data of ${variant.name} variant: [${clearDataCommand}]"
            def stdout = new ByteArrayOutputStream()
            exec {
                commandLine clearDataCommand
                standardOutput = stdout
            }
            String result = stdout.toString().trim()
            if (!result.startsWith("Success")) {
                println result
                throw new GradleException(clearDataCommand.join(" "))
            }
        }
    }
}
// Clear Application Data (once) before running instrumentation test
tasks.whenTaskAdded { task ->
    // Both of these targets are equivalent today, although in future connectedCheck
    // will also include connectedUiAutomatorTest (not implemented yet)
    if(task.name == "connectedAndroidTest" || task.name == "connectedCheck"){
        task.dependsOn(clearMainAppData)
    }
}
*/

printf('--------------\n')
printf('isMaster: %s\n', isMaster().toString())
printf('gitAvailable: %s\n', gitAvailable().toString())
printf('allCommitted: %s\n', allCommitted().toString())
printf('--------------\n')
if (isMaster() && !gitAvailable()) {
    throw new GradleException('GIT system is not available. On Windows try to run Android Studio as an Administrator. Check if GIT is installed and Studio have permissions to use it')
}
if (isMaster() && !allCommitted()) {
    throw new GradleException('There are uncommitted changes. Clone sources again as described in wiki and do not allow gradle update')
}