/*
 * Copyright (C) 2016 Glucosio Foundation
 *
 * This file is part of Glucosio.
 *
 * Glucosio is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, version 3.
 *
 * Glucosio is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with Glucosio.  If not, see <http://www.gnu.org/licenses/>.
 *
 *
 */

apply from: "${rootDir}/dependencies.gradle"
apply plugin: 'com.android.application'
apply plugin: 'jacoco'
apply plugin: 'realm-android'

android {
    compileSdkVersion buildConfig.compileSdk
    buildToolsVersion buildConfig.buildTools

    lintOptions {
        abortOnError false
    }

    defaultConfig {
        minSdkVersion buildConfig.minSdk
        targetSdkVersion buildConfig.targetSdk
        versionCode buildConfig.versionCode
        versionName buildConfig.versionName
        applicationId 'org.glucosio.android'

        vectorDrawables.useSupportLibrary = true
        testInstrumentationRunner 'android.support.test.runner.AndroidJUnitRunner'
    }

    buildTypes {
        debug {
            minifyEnabled false
            debuggable true

            versionNameSuffix '-DEVEL'
            applicationIdSuffix '.daily'

            testCoverageEnabled true

            buildConfigField 'String', 'GOOGLE_ANALYTICS_TRACKER', '"UA-68882401-2"'
            buildConfigField "String[]", "TRANSLATION_ARRAY", "new String[]{}"
        }

        release {
            debuggable false
            minifyEnabled true
            shrinkResources true
            zipAlignEnabled true

            buildConfigField 'String', 'GOOGLE_ANALYTICS_TRACKER', '"UA-68882401-2"'
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
            buildConfigField "String[]", "TRANSLATION_ARRAY", getAllLocales()
        }
    }

    lintOptions {
        abortOnError false
    }

    testOptions {
        unitTests.returnDefaultValues = true

        unitTests.all {
            jacoco {
                includeNoLocationClasses = true
            }
            // configure the test JVM arguments
            jvmArgs '-noverify'
        }

        unitTests {
            includeAndroidResources = true
        }
    }
}

repositories {
    mavenCentral()
    jcenter()
    maven { url 'https://jitpack.io' }
}

dependencies {
    wearApp project(':wear')

    // Android Support libraries
    implementation deps.android.support.wearable

    implementation deps.android.support.design
    implementation deps.android.support.cardView
    implementation deps.android.support.recyclerView
    implementation deps.android.support.percent

    // Google Play Services
    implementation deps.android.gms.analytics
    implementation deps.android.gms.drive
    implementation deps.android.gms.gcm
    implementation deps.android.gms.wearable

    // Firebase
    implementation deps.google.firebase.crash
    implementation deps.google.firebase.invites
    implementation deps.google.firebase.messaging

    // Other libraries
    implementation deps.ChrisJenx.calligraphy
    implementation deps.DanLew.androidJoda
    implementation(deps.MikePenz.materialDrawer) {
        transitive = true
    }
    implementation deps.PaoloRotolo.expandableHeightListView
    implementation deps.PhilJay.mpAndroidChart

    // Butterknife
    implementation deps.JakeWharton.butterKnife.core
    annotationProcessor deps.JakeWharton.butterKnife.compiler

    // Tests
    testImplementation deps.junit
    testImplementation deps.mockito
    testImplementation deps.square.assertJAndroid
    testImplementation deps.robolectric.core
    testImplementation deps.robolectric.shadows

    // This is for Mockito and Realm (TODO: find clean solution)
    testImplementation 'io.reactivex.rxjava2:rxjava:2.1.14'

    // Instrumental Tests
    androidTestImplementation deps.android.test.runner
    androidTestImplementation deps.android.test.rules
    androidTestImplementation deps.android.test.espresso.core
    androidTestImplementation deps.android.test.espresso.intents
    androidTestImplementation deps.android.test.espresso.contrib
}

def getAllLocales() {
    def foundLocales = new StringBuilder()
    foundLocales.append("new String[]{")

    fileTree("src/main/res").visit { FileVisitDetails details ->
        if (details.file.path.endsWith("strings.xml")) {
            def languageCode = details.file.parent.tokenize('/\\').last().replaceAll('values-', '').replaceAll('-r', '-')
            languageCode = (languageCode == "values") ? "en" : languageCode
            foundLocales.append("\"").append(languageCode).append("\"").append(",")
        }
    }

    foundLocales.append("}")
    //Don't forget to remove the trailing comma
    return foundLocales.toString().replaceAll(',}', '}')
}

apply plugin: 'com.google.gms.google-services'

def coverageSourceDirs = ['src/main/java']

task jacocoTestReport(type: JacocoReport, dependsOn: 'testDebugUnitTest') {
    group = 'Reporting'

    description = 'Generate Jacoco coverage reports'

    classDirectories = fileTree(dir: 'build/intermediates/classes/debug',
            excludes: ['**/R.class',
                       '**/R$*.class',
                       '**/*$ViewBinder*.*',
                       '**/*$InjectAdapter.*',
                       '**/BuildConfig.*',
                       '**/Manifest*.*',
                       'io/realm/**/*'])

    additionalSourceDirs = files(coverageSourceDirs)
    sourceDirectories = files(coverageSourceDirs)
    executionData = files('build/jacoco/testDebugUnitTest.exec')

    reports {
        xml.enabled = true
        html.enabled = true
        csv.enabled = false
    }
}

apply plugin: 'com.github.kt3k.coveralls'

coveralls {
    sourceDirs = files(['src/main/java']).files.absolutePath
    jacocoReportPath = 'build/reports/jacoco/jacocoTestReport/jacocoTestReport.xml'
}

// run: gradlew -PwithDexcount assembleDebug
def dexCount = project.hasProperty('withDexcount')
if (dexCount) {
    apply plugin: 'com.getkeepsafe.dexcount'

    dexcount {
        includeTotalMethodCount = true
    }
}
