/*
 * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
 * SPDX-License-Identifier: Apache-2.0
 */
import org.jetbrains.dokka.gradle.DokkaTask

apply from: rootProject.file('publishing.gradle')
apply plugin: 'com.android.library'
apply plugin: 'kotlin-android'
apply plugin: 'org.jetbrains.dokka'
apply plugin: 'jacoco'

def versionFile = new File(getProjectDir(), "version.properties")
Properties versionProperties = new Properties()
if (versionFile.exists()) {
    versionFile.withInputStream { instr ->
        versionProperties.load(instr)
    }
}

ext.versionMajor = versionProperties.getProperty('versionMajor') as Integer
ext.versionMinor = versionProperties.getProperty('versionMinor') as Integer
ext.versionPatch = versionProperties.getProperty('versionPatch') as Integer

android {
    compileSdk project.ext.chimeCompileSdkVersion
    defaultConfig {
        minSdkVersion project.ext.chimeMinSdkVersion
        targetSdkVersion project.ext.chimeTargetSdkVersion
        versionCode generateVersionCode()
        versionName generateVersionName()
        consumerProguardFiles 'consumer-rules.pro'
        renderscriptTargetApi 21
        renderscriptSupportModeEnabled true
    }

    kotlinOptions {
        jvmTarget = '1.8'
        freeCompilerArgs += ["-Xjvm-default=all"]
    }

    buildTypes {
        debug {
            buildConfigField("long", "VERSION_CODE", "${defaultConfig.versionCode}")
            buildConfigField("String", "VERSION_NAME", "\"${defaultConfig.versionName}\"")
            testCoverageEnabled true
        }
        release {
            buildConfigField("long", "VERSION_CODE", "${defaultConfig.versionCode}")
            buildConfigField("String", "VERSION_NAME", "\"${defaultConfig.versionName}\"")
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }

    testOptions {
        unitTests.all {
            jacoco {
                includeNoLocationClasses = true
            }
            jvmArgs(
                    "--add-opens", "java.base/java.util=ALL-UNNAMED",
                    "--add-opens", "java.base/java.lang.reflect=ALL-UNNAMED"
            )
        }
        // This causes system calls to return default (i.e. null or zero) values rather then
        // immediately throwing exceptions.  Without this, tests covering anything with significant OpenGLES or
        // EGL calls requires the unit test to basically mock every single line of the original file which is excessive
        // In return, unit tests should account for these null or 0 values and still mock where appropriate
        unitTests.returnDefaultValues = true
    }

    compileOptions {
        sourceCompatibility JavaVersion.VERSION_17
        targetCompatibility JavaVersion.VERSION_17
    }
    kotlinOptions {
        jvmTarget = '17'
    }
    namespace 'com.amazonaws.services.chime.sdk'

    defaultConfig {
        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }
}

tasks.withType(DokkaTask.class) {
    dokkaSourceSets.configureEach {
        documentedVisibilities.set([
                Visibility.PUBLIC,
                Visibility.PROTECTED
        ])
        skipEmptyPackages.set(true)
        skipDeprecated.set(true)

        perPackageOption {
            matchingRegex.set(".*internal.*")
            suppress.set(true)
        }
    }
}

tasks.withType(Test) {
    jacoco {
        includeNoLocationClasses = true
        excludes = ['jdk.internal.*'] // Allows it to run on Java 11
    }
}

task jacocoTestReport(type: JacocoReport, dependsOn: ['testDebugUnitTest','createDebugCoverageReport']) {
    group = "Reporting"
    description = "Generate Jacoco coverage reports after running tests."

    reports {
        xml.setRequired(true)
        html.setRequired(true)
    }

    def fileFilter = ['**/R.class', '**/R$*.class', '**/BuildConfig.*', '**/Manifest*.*', '**/*Test*.*', 'android/**/*.*']
    def kotlinTree = fileTree(dir: "$project.buildDir/tmp/kotlin-classes/debug", excludes: fileFilter)
    def mainSrc = "src/main/java"

    sourceDirectories.setFrom(files([mainSrc]))
    classDirectories.setFrom(files([kotlinTree]))
    executionData.setFrom(files([fileTree(dir: "$buildDir", includes: [
            "jacoco/testDebugUnitTest.exec",
            "outputs/code_coverage/debugAndroidTest/connected/**ec"]), "jacoco.exec"]))
}

tasks.withType(Test) {
    exclude "**/*DefaultActiveSpeakerDetectorTest*"
}

private Integer generateVersionCode() {
    return project.ext.chimeMinSdkVersion * 10000000 + ext.versionMajor * 10000 + ext.versionMinor * 100 + ext.versionPatch
}

private String generateVersionName() {
    return "${ext.versionMajor}.${ext.versionMinor}.${ext.versionPatch}"
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
    implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-core:1.3.3'
    implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:1.3.3'
    implementation 'androidx.core:core-ktx:1.2.0'
    implementation "androidx.lifecycle:lifecycle-runtime-ktx:2.9.2"
    implementation "androidx.lifecycle:lifecycle-process:2.9.2"
    api(name: 'amazon-chime-sdk-media', ext: 'aar') { transitive = true }
    api(name: 'amazon-chime-sdk-machine-learning', ext: 'aar') { transitive = true }
    implementation 'com.google.code.gson:gson:2.9.0'
    testImplementation 'org.jetbrains.kotlinx:kotlinx-coroutines-test:1.7.3'
    testImplementation 'junit:junit:4.13.2'
    testImplementation "io.mockk:mockk:1.13.12"
    testImplementation "org.robolectric:robolectric:4.10.3"
    // Android Test only
    androidTestImplementation 'androidx.test:core:1.6.1'
    androidTestImplementation 'androidx.test:runner:1.6.2'
    androidTestImplementation 'androidx.test.ext:junit:1.2.1'
    androidTestImplementation 'io.mockk:mockk-android:1.13.12'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.1.0'
}
