import com.android.ddmlib.DdmPreferences

apply plugin: 'jacoco'
apply plugin: 'com.android.application'
apply plugin: 'me.tatarka.retrolambda'
apply plugin: 'kotlin-android'
apply plugin: 'com.cookpad.android.licensetools'
apply plugin: 'com.github.ben-manes.versions'

// Manifest version
def versionMajor = 1
def versionMinor = 1
def versionPatch = 1

// CI
def isCi = "true".equals(System.getenv("CI"))
def preDexEnabled = "true".equals(System.getProperty("pre-dex", "true"))

def packageName = "io.github.droidkaigi.confsched2017"

// for debug info
def gitSha = 'git rev-parse --short HEAD'.execute([], project.rootDir).text.trim()
def gitBranch = (System.getenv("CIRCLE_BRANCH") != null) ? System.getenv("CIRCLE_BRANCH") :
        'git rev-parse --abbrev-ref HEAD'.execute([], project.rootDir).text.trim()
def buildTime = new Date().format("yyyy-MM-dd'T'HH:mm'Z'", TimeZone.getTimeZone("UTC"))

android {
    compileSdkVersion compile_sdk_version as int
    buildToolsVersion build_tools_version
    dataBinding {
        enabled = true
    }

    dexOptions {
        // Skip pre-dexing when running on CI or when disabled via -Dpre-dex=false.
        preDexLibraries = preDexEnabled && !isCi
    }

    defaultConfig {
        applicationId packageName
        minSdkVersion min_sdk_version as int
        targetSdkVersion target_sdk_version as int
        versionCode versionMajor * 10000 + versionMinor * 100 + versionPatch
        versionName "${versionMajor}.${versionMinor}.${versionPatch}"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"

        buildConfigField "String", "CONFERENCE_TIMEZONE", "\"Asia/Tokyo\""
        buildConfigField "String", "API_ROOT", "\"https://droidkaigi.github.io/2017/\""
        buildConfigField "String", "STATIC_ROOT", "\"https://droidkaigi.github.io/2017\""
        buildConfigField "String", "GIT_SHA", "\"${gitSha}\""
        buildConfigField "String", "GIT_BRANCH", "\"${gitBranch}\""
        buildConfigField "String", "BUILD_TIME", "\"${buildTime}\""

        // Referred to https://github.com/circleci/EspressoSample to make the Espresso tests work on CircleCI.
        DdmPreferences.setTimeOut(60000)

        vectorDrawables.useSupportLibrary = true
    }

    packagingOptions {
        exclude 'META-INF/NOTICE.txt'
        exclude 'META-INF/LICENSE.txt'
        exclude 'META-INF/DEPENDENCIES'
        exclude 'META-INF/NOTICE'
        exclude 'META-INF/LICENSE'
        exclude 'META-INF/services/javax.annotation.processing.Processor'
        exclude 'META-INF/rxjava.properties'
    }

    signingConfigs {
        debug {
            storeFile rootProject.file("debug.keystore")
            storePassword "android"
            keyAlias "androiddebugkey"
            keyPassword "android"
        }
        release {
            storeFile rootProject.file("release.keystore")
            storePassword System.getenv("RELEASE_STORE_PASSWORD")
            keyAlias System.getenv("RELEASE_KEY_ALIAS")
            keyPassword System.getenv("RELEASE_KEY_PASSWORD")
        }
    }

    buildTypes {
        debug {
            signingConfig signingConfigs.debug
            applicationIdSuffix '.debug'
            versionNameSuffix "-debug"
            debuggable true
            zipAlignEnabled true
            testCoverageEnabled true
        }
        release {
            signingConfig signingConfigs.release
            debuggable false
            zipAlignEnabled true
            minifyEnabled true
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }

    productFlavors {
        develop {
            applicationId "${packageName}.develop"
        }
        production {
            applicationId packageName
        }
    }

    lintOptions {
        disable 'InvalidPackage'
        abortOnError false
        textReport true
        textOutput 'stdout'
        lintConfig file("lint.xml")
    }

    aaptOptions {
        noCompress 'apk'
    }

    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }

    testOptions {
        unitTests.all {
            // configure the set of classes for JUnit tests
            include project.hasProperty("testFilter") ? "**/*${project.ext.testFilter}*Test.class" : '**/*Test.class'
            exclude '**/espresso/**/*.class'

            // configure max heap size of the test JVM
            maxHeapSize = '2048m'

            // configure the test JVM arguments
            jvmArgs '-XX:MaxPermSize=512m', '-XX:-UseSplitVerifier'

            // Specify max number of processes (default is 1)
            maxParallelForks = 1

            // Specify max number of test classes to execute in a test process
            // before restarting the process (default is unlimited)
            forkEvery = 150

            // configure whether failing tests should fail the build
            ignoreFailures false

            systemProperty 'robolectric.logging.enabled', 'true'

            testLogging {
                events 'passed', 'skipped', 'failed', 'standardError'
            }
            jacoco {
                includeNoLocationClasses = true
            }
        }
    }
}

configurations {
    all {
        resolutionStrategy {
            force "com.android.support:support-annotations:${support_lib_version}"
        }
    }
}

dependencies {
    // Support Library
    compile "com.android.support:support-v4:${support_lib_version}"
    compile "com.android.support:appcompat-v7:${support_lib_version}"
    compile "com.android.support:support-annotations:${support_lib_version}"
    compile "com.android.support:design:${support_lib_version}"
    compile "com.android.support:recyclerview-v7:${support_lib_version}"
    compile "com.android.support:cardview-v7:${support_lib_version}"
    compile "com.android.support:customtabs:${support_lib_version}"
    compile "com.android.support:support-vector-drawable:${support_lib_version}"
    compile "com.android.support:animated-vector-drawable:${support_lib_version}"
    compile 'com.android.support.constraint:constraint-layout:1.0.1'

    // Firebase(analytics, crash report)
    compile 'com.google.firebase:firebase-core:10.0.1'
    compile 'com.google.firebase:firebase-crash:10.0.1'

    // Network
    compile 'com.squareup.retrofit2:retrofit:2.2.0'
    compile 'com.squareup.retrofit2:adapter-rxjava2:2.2.0'
    compile 'com.squareup.retrofit2:converter-gson:2.2.0'
    compile 'com.google.code.gson:gson:2.8.0'
    compile 'com.squareup.okhttp3:okhttp:3.4.1'

    // Structure
    compile 'com.google.dagger:dagger:2.9'
    annotationProcessor 'com.google.dagger:dagger-compiler:2.9'
    provided 'javax.annotation:jsr250-api:1.0'
    compile 'io.reactivex.rxjava2:rxjava:2.0.5'
    compile 'io.reactivex.rxjava2:rxandroid:2.0.1'
    compile 'com.annimon:stream:1.1.5'
    compile 'uk.co.chrisjenx:calligraphy:2.2.0'

    // Android Utility
    compile 'com.deploygate:sdk:3.1.1'
    compile 'com.jakewharton.timber:timber:4.5.1'
    debugCompile 'com.facebook.stetho:stetho:1.4.2'
    debugCompile 'com.facebook.stetho:stetho-okhttp3:1.4.2'
    debugCompile 'com.facebook.stetho:stetho-timber:1.4.2@aar'
    compile 'com.squareup.picasso:picasso:2.5.2'
    annotationProcessor 'com.github.gfx.android.orma:orma-processor:4.2.0'
    compile 'com.github.gfx.android.orma:orma:4.2.0'
    compile 'com.rejasupotaro:kvs-schema:5.0.1'
    annotationProcessor 'com.rejasupotaro:kvs-schema-compiler:5.0.1'
    compile 'com.github.sys1yagi.fragment-creator:library:0.8.2'
    annotationProcessor 'com.github.sys1yagi.fragment-creator:processor:0.8.2'

    // UI
    compile 'org.lucasr.twowayview:core:1.0.0-SNAPSHOT@aar'
    compile 'org.lucasr.twowayview:layouts:1.0.0-SNAPSHOT@aar'
    compile 'com.google.android:flexbox:0.2.5'
    compile 'net.opacapp:multiline-collapsingtoolbar:1.3.1'
    compile 'com.github.chrisbanes:PhotoView:1.3.1'

    // Debug
    debugCompile 'com.squareup.leakcanary:leakcanary-android:1.5'
    releaseCompile 'com.squareup.leakcanary:leakcanary-android-no-op:1.5'
    testCompile 'com.squareup.leakcanary:leakcanary-android-no-op:1.5'
    debugCompile 'com.tomoima.debot:debot:2.0.2'
    releaseCompile 'com.tomoima.debot:debot-no-op:2.0.2'

    // fps, track the frame rate of animation view.
    debugCompile 'jp.wasabeef:takt:1.0.3'

    // Test
    testCompile 'junit:junit:4.12'
    testCompile "org.robolectric:robolectric:3.2.2"
    testCompile 'com.squareup.assertj:assertj-android:1.1.1'
    testCompile 'org.mockito:mockito-core:2.7.0'
    androidTestCompile 'org.mockito:mockito-android:2.7.0'
    androidTestCompile 'com.android.support.test:runner:0.5'
    androidTestCompile 'com.android.support.test:rules:0.5'
    androidTestCompile 'com.squareup.assertj:assertj-android:1.1.1'
    androidTestCompile 'com.android.support.test.espresso:espresso-core:2.2.2'
    androidTestCompile 'com.android.support.test.espresso:espresso-intents:2.2.2'
    testCompile 'junit:junit:4.12'
    testCompile "org.jetbrains.kotlin:kotlin-stdlib:1.0.6"
    testCompile "org.jetbrains.kotlin:kotlin-test-junit:1.0.6"
    testCompile 'com.taroid.knit:knit:0.1.2'
    testCompile 'com.github.sys1yagi:kmockito:0.1.2'
}

jacoco {
    toolVersion = "0.7.7.201606060606"
}

// A list of directories which should be included in coverage report
def coverageSourceDirs = ['src/main/java']
// A list of files which should be excluded from coverage report since they are generated and/or framework code
def coverageExcludeFiles = ['**/R.class', '**/R$*.class', '**/DataBindingInfo.class', '**/android/databinding/*.*', '**/com/android/**/*.*', '**/BR.class']

task jacocoTestReportProduction(type: JacocoReport, dependsOn: ['testProductionDebugUnitTest']) {
    group = "Reporting"
    description = "Generate Jacoco coverage reports after running tests."
    reports {
        xml.enabled true
        html.enabled true
        csv.enabled false
        xml.destination "${buildDir}/reports/jacoco/test/jacocoTestReportProd.xml"
        html.destination "${buildDir}/reports/coverage/prod"
        classDirectories = files(
                fileTree(
                        dir: "${buildDir}/intermediates/classes/production/debug",
                        exclude: coverageExcludeFiles))
    }
    sourceDirectories = files(coverageSourceDirs)
    executionData = files "${buildDir}/jacoco/testProductionDebugUnitTest.exec"

    doLast {
        println "jacoco xml report has been generated to file://${buildDir}/reports/jacoco/test/jacocoTestReportProd.xml"
        println "jacoco html report has been generated to file://${reports.html.destination}/index.html"
    }
}

task jacocoTestReportDevelop(type: JacocoReport, dependsOn: ['testDevelopDebugUnitTest']) {
    group = "Reporting"
    description = "Generate Jacoco coverage reports after running tests."
    reports {
        xml.enabled true
        html.enabled true
        csv.enabled false
        xml.destination "${buildDir}/reports/jacoco/test/jacocoTestReportDevelop.xml"
        html.destination "${buildDir}/reports/coverage/develop"
        classDirectories = files(
                fileTree(
                        dir: "${buildDir}/intermediates/classes/develop/debug",
                        exclude: coverageExcludeFiles))
    }
    sourceDirectories = files(coverageSourceDirs)
    executionData = files "${buildDir}/jacoco/testDevelopDebugUnitTest.exec"

    doLast {
        println "jacoco xml report has been generated to file://${buildDir}/reports/jacoco/test/jacocoTestReportDevelop.xml"
        println "jacoco html report has been generated to file://${reports.html.destination}/index.html"
    }
}

tasks['check'].dependsOn checkLicenses

// report only stable versions
dependencyUpdates.resolutionStrategy = {
    componentSelection { rules ->
        rules.all { ComponentSelection selection ->
            boolean rejected = ['alpha', 'beta', 'rc', 'cr', 'm'].any { qualifier ->
                selection.candidate.version ==~ /(?i).*[.-]${qualifier}[.\d-]*/
            }
            if (rejected) {
                selection.reject('Release candidate')
            }
        }
    }
}

// MUST BE AT THE BOTTOM
apply plugin: 'com.google.gms.google-services'
