buildscript {
    repositories {
        jcenter()
    }

    dependencies {
        classpath 'com.dicedmelon.gradle:jacoco-android:0.1.4'
    }
}
apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'
apply plugin: 'kotlin-kapt'
apply plugin: 'com.google.gms.google-services'
apply plugin: 'jacoco-android'
apply plugin: 'com.google.firebase.crashlytics'

jacoco {
    toolVersion = "0.8.3"
}

ext {
    powermockVersion = "1.7.3"
    dexmakerVersion = "1.2"
    retrofit2Version = '2.9.0'
    okhttp3Version = '4.7.2'
}


repositories {
    jcenter { url "https://jcenter.bintray.com/" }
    mavenCentral()
}

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 allCommited = { ->
    StringBuilder stringBuilder = new StringBuilder()
    try {
        def stdout = new ByteArrayOutputStream()
        exec {
            commandLine 'git', 'status', '-s'
            standardOutput = stdout
        }
        String commitObject = stdout.toString().trim()
        stringBuilder.append(commitObject)
    } catch (ignored) {
        return false // NoGitSystemAvailable
    }
    return stringBuilder.toString().isEmpty()

}

tasks.matching { it instanceof Test }.all {
    testLogging.events = ["failed", "skipped", "started"]
    testLogging.exceptionFormat = "full"
}

android {
    compileSdkVersion 28
    ndkVersion "21.1.6352462"

    defaultConfig {
        minSdkVersion 24
        targetSdkVersion 28
        multiDexEnabled true
        versionCode 1500
        version "2.6.7-dev"
        buildConfigField "String", "VERSION", '"' + version + '"'
        buildConfigField "String", "BUILDVERSION", '"' + generateGitBuild() + '-' + generateDate() + '"'
        buildConfigField "String", "REMOTE", '"' + generateGitRemote() + '"'
        buildConfigField "String", "HEAD", '"' + generateGitBuild() + '"'
        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
        // if you change minSdkVersion to less than 11, you need to change executeTask for wear

        ndk {
            moduleName "BleCommandUtil"
        }
    }
    kotlinOptions {
        jvmTarget = '1.8'
    }
    lintOptions {
        checkReleaseBuilds false
        disable 'MissingTranslation'
        disable 'ExtraTranslation'
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
        debug {
            testCoverageEnabled(project.hasProperty('coverage'))
        }
        firebaseDisable {
            System.setProperty("disableFirebase", "true")
            ext.enableCrashlytics = false
        }
    }
    productFlavors {
        flavorDimensions "standard"
        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"
            ]
        }
    }
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }

    testOptions {
        unitTests {
            returnDefaultValues = true
            includeAndroidResources = true

            all {
                maxParallelForks = 10
                forkEvery = 20
            }
        }
    }

    useLibrary "org.apache.http.legacy"

    configurations.all {
        resolutionStrategy.force 'com.google.code.findbugs:jsr305:1.3.9'
    }
}

allprojects {
    repositories {
        jcenter()
        flatDir {
            dirs 'libs'
        }
        maven { url 'https://jitpack.io' }
    }
}

dependencies {
    wearApp project(':wear')

    implementation project(':core')
    implementation project(':dana')
    implementation project(':danars')
    implementation project(':danar')

    implementation fileTree(include: ['*.jar'], dir: 'libs')
    implementation 'com.google.android.gms:play-services-wearable:17.0.0'
    implementation "com.google.android.gms:play-services-location:17.0.0"
    implementation 'com.google.firebase:firebase-core:17.4.2'
    implementation 'com.google.firebase:firebase-auth:19.3.1'
    implementation 'com.google.firebase:firebase-database:19.3.0'

    implementation 'androidx.appcompat:appcompat:1.1.0'
    implementation 'androidx.legacy:legacy-support-v13:1.0.0'
    implementation 'androidx.legacy:legacy-support-v4:1.0.0'
    implementation 'androidx.cardview:cardview:1.0.0'
    implementation 'androidx.biometric:biometric:1.0.1'
    implementation 'androidx.recyclerview:recyclerview:1.1.0'
    implementation 'androidx.gridlayout:gridlayout:1.0.0'
    implementation 'androidx.percentlayout:percentlayout:1.0.0'
    implementation "androidx.preference:preference-ktx:1.1.1"
    implementation "androidx.activity:activity-ktx:${activityVersion}"
    implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
    implementation 'com.google.android.material:material:1.1.0'

    implementation "io.reactivex.rxjava2:rxandroid:${rxandroid_version}"

    implementation "com.j256.ormlite:ormlite-core:${ormLiteVersion}"
    implementation "com.j256.ormlite:ormlite-android:${ormLiteVersion}"
    implementation("com.github.tony19:logback-android-classic:1.1.1-6") {
        exclude group: "com.google.android", module: "android"
    }
    implementation 'org.apache.commons:commons-lang3:3.10'
    implementation 'org.slf4j:slf4j-api:1.7.30'
    // Graphview cannot be upgraded
    implementation "com.jjoe64:graphview:4.0.1"
    implementation "com.joanzapata.iconify:android-iconify-fontawesome:2.2.2"
    implementation 'com.madgag.spongycastle:core:1.58.0.0'
    // Omnipod wizard
    implementation(name: "com.atech-software.android.library.wizardpager-1.1.1", ext: "aar")

    implementation("com.google.android:flexbox:0.3.0") {
        exclude group: "com.android.support"
    }
    implementation("io.socket:socket.io-client:1.0.0") {
        // excluding org.json which is provided by Android
        exclude group: "org.json", module: "json"
    }
    implementation "com.google.code.gson:gson:2.8.6"
    implementation('com.google.guava:guava:29.0-jre') {
        exclude group: "com.google.code.findbugs", module: "jsr305"
    }
    implementation 'com.google.code.findbugs:jsr305:3.0.2'

    implementation 'net.danlew:android.joda:2.10.6'

    implementation 'org.mozilla:rhino:1.7.12'

    implementation 'com.github.DavidProdinger:weekdays-selector:1.1.0'

    implementation 'com.github.kenglxn.QRGen:android:2.6.0'
    implementation 'com.eatthepath:java-otp:0.2.0'

    testImplementation "junit:junit:4.13"
    testImplementation 'org.json:json:20200518'
    testImplementation "org.mockito:mockito-core:2.8.47"
    testImplementation "org.powermock:powermock-api-mockito2:${powermockVersion}"
    testImplementation "org.powermock:powermock-module-junit4-rule-agent:${powermockVersion}"
    testImplementation "org.powermock:powermock-module-junit4-rule:${powermockVersion}"
    testImplementation "org.powermock:powermock-module-junit4:${powermockVersion}"
    testImplementation 'joda-time:joda-time:2.10.6'
    testImplementation('com.google.truth:truth:1.0.1') {
        exclude group: "com.google.guava", module: "guava"
        exclude group: "com.google.code.findbugs", module: "jsr305"
    }
    testImplementation "org.skyscreamer:jsonassert:1.5.0"
    testImplementation "org.hamcrest:hamcrest-all:1.3"

    implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
    implementation "org.jetbrains.kotlin:kotlin-reflect:$kotlin_version"
    implementation "org.jetbrains.kotlinx:kotlinx-coroutines-core:$coroutinesVersion"
    implementation "org.jetbrains.kotlinx:kotlinx-coroutines-android:$coroutinesVersion"

    // new for tidepool
    implementation "com.squareup.okhttp3:okhttp:$okhttp3Version"
    implementation "com.squareup.okhttp3:logging-interceptor:$okhttp3Version"
    implementation "com.squareup.retrofit2:retrofit:$retrofit2Version"
    implementation "com.squareup.retrofit2:adapter-rxjava2:$retrofit2Version"
    implementation "com.squareup.retrofit2:converter-gson:$retrofit2Version"

    // Phone checker
    implementation 'com.scottyab:rootbeer-lib:0.0.8'
    
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.3.0-alpha03'
    androidTestImplementation 'androidx.test.ext:junit:1.1.1'
    androidTestImplementation 'androidx.test:rules:1.3.0-beta01'
    androidTestImplementation 'com.google.code.findbugs:jsr305:3.0.2'

    /* Dagger2 - We are going to use dagger.android which includes
    * support for Activity and fragment injection so we need to include
    * the following dependencies */
    implementation "com.google.dagger:dagger-android:$dagger_version"
    implementation "com.google.dagger:dagger-android-support:$dagger_version"
    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"

    androidTestImplementation 'androidx.test.uiautomator:uiautomator:2.2.0'
}

/*
// 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('allCommited: %s\n', allCommited().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() && !allCommited()) {
    throw new GradleException('There are uncommitted changes. Clone sources again as described in wiki and do not allow gradle update')
}