plugins {
    id 'com.android.application'
    id 'kotlin-android'
    id 'kotlin-kapt'
    id 'kotlin-allopen'
    id 'kotlinx-serialization'
    id 'com.google.gms.google-services'
    id 'com.google.firebase.crashlytics'
    id 'com.vanniktech.dependency.graph.generator'

}

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

repositories {
    mavenCentral()
    google()
}

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()
    // showing only date prevents app to rebuild everytime
    stringBuilder.append((new Date()).format('yyyy.MM.dd'))
    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()
}

android {

    namespace 'app.aaps'
    ndkVersion "21.1.6352462"

    defaultConfig {
        multiDexEnabled true
        versionCode 1500
        version "3.2.0-dev-m"
        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", "AAPS"
            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"
            ]
        }
        aapsclient {
            applicationId "info.nightscout.aapsclient"
            dimension "standard"
            resValue "string", "app_name", "AAPSClient"
            versionName version + "-aapsclient"
            manifestPlaceholders = [
                    appIcon     : "@mipmap/ic_yellowowl",
                    appIconRound: "@mipmap/ic_yellowowl"
            ]
        }
        aapsclient2 {
            applicationId "info.nightscout.aapsclient2"
            dimension "standard"
            resValue "string", "app_name", "AAPSClient2"
            versionName version + "-aapsclient"
            manifestPlaceholders = [
                    appIcon     : "@mipmap/ic_blueowl",
                    appIconRound: "@mipmap/ic_blueowl"
            ]
        }
    }

    useLibrary "org.apache.http.legacy"

    dataBinding {   //Deleting it causes a binding error
        enabled = true
    }
}

allprojects {
    repositories {
    }
}

dependencies {
    wearApp project(':wear')

    // in order to use internet's versions you'd need to enable Jetifier again
    // https://github.com/nightscout/graphview.git
    // https://github.com/nightscout/iconify.git
    implementation project(':shared:impl')
    implementation project(':core:main')
    implementation project(':core:graphview')
    implementation project(':core:interfaces')
    implementation project(':core:libraries')
    implementation project(':core:nssdk')
    implementation project(':core:utils')
    implementation project(':core:ui')
    implementation project(':core:validators')
    implementation project(':ui')
    implementation project(':plugins:aps')
    implementation project(':plugins:automation')
    implementation project(':plugins:configuration')
    implementation project(':plugins:constraints')
    implementation project(':plugins:insulin')
    implementation project(':plugins:main')
    implementation project(':plugins:sensitivity')
    implementation project(':plugins:smoothing')
    implementation project(':plugins:source')
    implementation project(':plugins:sync')
    implementation project(':implementation')
    implementation project(':database:entities')
    implementation project(':database:impl')
    implementation project(':pump:combo')
    implementation project(':pump:combov2')
    implementation project(':pump:dana')
    implementation project(':pump:danars')
    implementation project(':pump:danar')
    implementation project(':pump:diaconn')
    implementation project(':pump:eopatch')
    implementation project(':pump:medtrum')
    implementation project(':insight')
    implementation project(':pump:medtronic')
    implementation project(':pump:pump-common')
    implementation project(':pump:omnipod-common')
    implementation project(':pump:omnipod-eros')
    implementation project(':pump:omnipod-dash')
    implementation project(':pump:rileylink')
    implementation project(':pump:virtual')
    implementation project(':workflow')

    testImplementation project(':shared:tests')

    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 */
    kapt "com.google.dagger:dagger-android-processor:$dagger_version"
    kapt "com.google.dagger:dagger-compiler:$dagger_version"

    // MainApp
    api "com.uber.rxdogtag2:rxdogtag:2.0.2"

}

apply from: "${project.rootDir}/core/main/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')
}