apply plugin: 'com.android.application'
apply plugin: 'io.fabric'
apply plugin: 'kotlin-android'

dependencies {
    compile 'com.android.support:multidex:1.0.1'

    compile "com.google.android.gms:play-services-maps:${play_services_version}"
    compile "com.google.android.gms:play-services-location:${play_services_version}"
    compile "com.google.android.gms:play-services-analytics:${play_services_version}"

    compile "com.android.support:support-v4:${support_lib_version}"
    compile "com.android.support:appcompat-v7:${support_lib_version}"
    compile "com.android.support:preference-v7:${support_lib_version}"
    compile "com.android.support:preference-v14:${support_lib_version}"
    compile "com.android.support:cardview-v7:${support_lib_version}"
    compile "com.android.support:recyclerview-v7:${support_lib_version}"
    compile "com.android.support:design:${support_lib_version}"

    // Android library to display the changelog
    compile 'com.github.gabrielemariotti.changeloglib:changelog:2.0.0'

    //DroneKit-Android client lib
    compile 'com.o3dr.android:dronekit-android:3.0.2'
    //Comment line above, and uncomment line below to use your local version of the dronekit-android client lib
    //Don't forget to uncomment the lines in the settings.gradle file as well.
//     compile project(':ClientLib')

    compile 'me.grantland:autofittextview:0.2.1'
    compile(name:'shimmer-android-release', ext:'aar')
    compile(name:'libuvccamera-release', ext:'aar')
    compile(name:'sliding-up-panel-3.3.0', ext:'aar')

    compile files('libs/droneapi-java-0.3-SNAPSHOT.jar')
    compile files('libs/protobuf-java-2.5.0.jar')
    compile files('libs/jeromq-0.3.4.jar')
    compile files('libs/sius-0.3.1-SNAPSHOT.jar')
    compile files('libs/BaiduLBS_Android.jar')

    compile "com.squareup.okhttp:okhttp:${okhttp_version}"
    compile "com.squareup.okhttp:okhttp-urlconnection:${okhttp_version}"

    compile 'com.jakewharton.timber:timber:3.1.0'
    compile "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
    compile('com.crashlytics.sdk.android:crashlytics:2.5.5@aar') {
        transitive = true;
    }

    //Charts and graph library
    compile 'com.github.lecho:hellocharts-library:1.5.5@aar'

    //Leak canary (https://github.com/square/leakcanary)
    debugCompile 'com.squareup.leakcanary:leakcanary-android:1.4-beta2'
    releaseCompile 'com.squareup.leakcanary:leakcanary-android-no-op:1.4-beta2'
    testCompile 'com.squareup.leakcanary:leakcanary-android-no-op:1.4-beta2'
}

def versionPrefix = "Tower-v"

//Decomposed version name and code (https://plus.google.com/+JakeWharton/posts/6f5TcVPRZij)
def versionMajor = 4
def versionMinor = 0
def versionPatch = 0
def versionBuild = 10 //bump for dogfood builds, public betas, etc.

//Logging levels
def logLevelVerbose = 2;
def logLevelDebug = 3;
def logLevelInfo = 4;
def logLevelWarn = 5;
def logLevelError = 6;
def logLevelAssert = 7;

android {
    compileSdkVersion android_build_sdk_version
    buildToolsVersion android_build_tools_version

    dexOptions {
        javaMaxHeapSize "4g"
    }

    defaultConfig {
        applicationId 'org.droidplanner.android'
        minSdkVersion android_build_min_sdk_version
        targetSdkVersion android_build_target_sdk_version
        versionCode computeVersionCode(versionMajor, versionMinor, versionPatch, versionBuild)
        versionName generateVersionName(versionPrefix, versionMajor, versionMinor, versionPatch)

        buildConfigField "boolean", "WRITE_LOG_FILE", "true"
        buildConfigField "int", "LOG_FILE_LEVEL", "$logLevelDebug"
        buildConfigField "boolean", "ENABLE_CRASHLYTICS", "false"

        //Manifest placeholders (http://tools.android.com/tech-docs/new-build-system/user-guide/manifest-merger#TOC-Placeholder-support)
        manifestPlaceholders = [
            fabricApiKey:getFabricApiKey()
        ]

        // Enabling multidex support.
        multiDexEnabled true

    }

    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_7
        targetCompatibility JavaVersion.VERSION_1_7
    }

    sourceSets {
        main {
            manifest.srcFile 'AndroidManifest.xml'
            java.srcDirs = ['src']
            resources.srcDirs = ['src']
            aidl.srcDirs = ['src']
            renderscript.srcDirs = ['src']
            res.srcDirs = ['res']
            assets.srcDirs = ['assets']

            jniLibs.srcDir "jni/libs"
        }

        // Move the build types to build-types/<type>
        // For instance, build-types/debug/java, build-types/debug/AndroidManifest.xml, ...
        // This moves them out of them default location under src/<type>/... which would
        // conflict with src/ being used by the main source set.
        // Adding new build types or product flavors should be accompanied
        // by a similar customization.
        debug.setRoot('build-types/debug')
        release.setRoot('build-types/release')
    }

    //FIXME: remove this after lint errors have been taken care of
    lintOptions {
        abortOnError false
    }

    signingConfigs {
        release {
            storeFile getAppKeystoreFile()
            storePassword getAppKeystorePassword()
            keyAlias getAppKey()
            keyPassword getAppKeyPassword()
        }
    }

    android.applicationVariants.all { variant ->
        variant.outputs.each { output ->
            def file = output.outputFile
            if (file != null && file.name.endsWith('.apk')) {
                def buildType = variant.buildType.getName()
                def flavorName = variant.getFlavorName()
                def versionCode = defaultConfig.versionCode
                output.outputFile = new File(file.parent, "tower-${flavorName}-${buildType}.${versionCode}.apk")
            }
        }
    }

    android.variantFilter { variant ->
        def flavors = variant.getFlavors()
        if (!flavors.isEmpty()) {
            def flavorName = flavors.get(0).name
            def buildTypeName = variant.buildType.name

            //Filter out the variants we're not interested in building.
            def ignoreVariant = true
            switch (buildTypeName) {
                case "release":
                    switch (flavorName) {
                        case "prod":
                        case "beta":
                            ignoreVariant = false
                            break
                    }
                    break;

                case "debug":
                    switch (flavorName) {
                        case "dev":
                            ignoreVariant = false
                            break
                    }
                    break;
            }

            variant.setIgnore(ignoreVariant);
        }
    }

    productFlavors {
        dev {
            applicationIdSuffix ".debug"
            resValue "string", "app_title", "Tower Dev"
            resValue "string", "baidu_api_key", ""
            versionName generateVersionName(versionPrefix, versionMajor, versionMinor, versionPatch, "debug.${versionBuild}")

            //Enable or disable crashlytics based on the availability of the api key
            ext.enableCrashlytics = false
        }

        beta {
            applicationIdSuffix ".beta"
            resValue "string", "app_title", "Tower Beta"
            resValue "string", "baidu_api_key", "4x7A3lUHEmzFxosafDa4bLP7yinmEnPh"
            versionName generateVersionName(versionPrefix, versionMajor, versionMinor, versionPatch, "beta.${versionBuild}")

            //Enable or disable crashlytics based on the availability of the api key
            ext.enableCrashlytics = hasFabricApiKey()
        }

        prod {
            resValue "string", "app_title", "Tower"
            resValue "string", "baidu_api_key", "41mPy2URFjOL61GzyWk8U5oLhhwSYGWe"
            buildConfigField "boolean", "WRITE_LOG_FILE", "false"

            //Enable or disable crashlytics based on the availability of the api key
            ext.enableCrashlytics = hasFabricApiKey()
        }
    }

    buildTypes {
        debug {
            buildConfigField "boolean", "ENABLE_CRASHLYTICS", "false"
        }

        release {
            signingConfig signingConfigs.release
            buildConfigField "boolean", "ENABLE_CRASHLYTICS", "${hasFabricApiKey()}"
        }
    }
    buildToolsVersion '24.0.1'
}

/**
 * @return The most recent git tag to be used as version name for the app.
 */
def getGitVersion(){
    def cmd = "git describe --tag"
    try {
        def proc = cmd.execute()
        return proc.text.trim()
    }catch(IOException e){
        //Unable to find 'git'
        return "please update version name manually"
    }
}

def getAppKeystoreFile() {
    def filePath = hasProperty('ORG_DROIDPLANNER_ANDROID_KEYSTORE') ? ORG_DROIDPLANNER_ANDROID_KEYSTORE : null
    return filePath ? file(filePath) : null
}

def getAppKeystorePassword(){
    return hasProperty('ORG_DROIDPLANNER_ANDROID_KEYSTORE_PWD') ? ORG_DROIDPLANNER_ANDROID_KEYSTORE_PWD : ''
}

def getAppKeyPassword() {
    return hasProperty('ORG_DROIDPLANNER_ANDROID_KEY_PWD') ? ORG_DROIDPLANNER_ANDROID_KEY_PWD : ''
}

def getAppKey() {
    return hasProperty('ORG_DROIDPLANNER_ANDROID_KEY_ALIAS') ? ORG_DROIDPLANNER_ANDROID_KEY_ALIAS : ''
}

def getFabricApiKey(){
    return hasFabricApiKey() ? COM_O3DR_FABRIC_API_KEY : ''
}

def hasFabricApiKey(){
    return hasProperty('COM_O3DR_FABRIC_API_KEY')
}
