apply plugin: 'com.android.library'
apply plugin: 'jacoco'
apply plugin: 'kotlin-android'
apply plugin: 'maven-publish'

/**
 * Extra properties used by the project.
 */
ext {
    // String property to store the proper name of the mediation network adapter.
    adapterName = "Mintegral"
    // String property to store version name.
    stringVersion = "16.9.91.1"
    // String property to store group id.
    stringGroupId = "com.google.ads.mediation"
    // Jacoco version to generate code coverage data
    jacocoVersion = '0.8.8'
}

android {
    namespace 'com.google.ads.mediation.mintegral'
    compileSdk 34
    defaultConfig {
        minSdkVersion 23
        targetSdk 33
        versionCode 16099101
        versionName stringVersion
        buildConfigField('String', 'ADAPTER_VERSION', "\"${stringVersion}\"")
        multiDexEnabled true
    }

    compileOptions {
        sourceCompatibility JavaVersion.VERSION_11
        targetCompatibility JavaVersion.VERSION_11
    }

    kotlinOptions {
        jvmTarget = JavaVersion.VERSION_11.toString()
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
        debug {
            testCoverageEnabled true
        }
    }

    buildFeatures {
        buildConfig true
    }

    sourceSets {
        test.java.srcDirs += 'src/test/java'
    }

    testOptions {
        unitTests {
            all {
                jvmArgs "-noverify"
            }
            includeAndroidResources = true
            unitTests.returnDefaultValues = true
        }
    }
}

tasks.withType(Test) {
    testLogging {
        events "PASSED", "SKIPPED", "FAILED"
        exceptionFormat = 'full'
    }
    jacoco.includeNoLocationClasses = true
    jacoco.excludes = ['jdk.internal.*']
    finalizedBy jacocoTestReport
}

jacoco {
    toolVersion= "$jacocoVersion"
}

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

    reports {
        xml.required = true
        html.required = true
    }

    def fileFilter = ['androidx/**/*.*',
                      '**/view/*.*',
                      '**/data/*.*',
                      '**/data/model/*.*',
                      '**/generated/callback/*.*',
                      '**/lambda$*.class',
                      '**/lambda.class',
                      '**/*lambda.class',
                      '**/*lambda*.class']

    def debugTree = fileTree(dir:
            "${buildDir}/intermediates/javac/debug/classes",
            excludes: fileFilter
    )

    def mainSrc = "$project.projectDir/src/main/java"

    getSourceDirectories().setFrom(files([mainSrc]))
    getClassDirectories().setFrom(files([debugTree]))
    getExecutionData().setFrom(fileTree(dir: "${buildDir}", includes:[
            "/outputs/unit_test_code_coverage/debugUnitTest/testDebugUnitTest.exec"]))
}

dependencies {
    implementation 'com.google.android.gms:play-services-ads:24.5.0'
    implementation 'androidx.annotation:annotation:1.5.0'
    implementation 'com.mbridge.msdk.oversea:mbridge_android_sdk:16.9.91'

    // Jacoco
    implementation "org.jacoco:org.jacoco.core:$jacocoVersion"

    // Unit tests
    testImplementation 'junit:junit:4.13.2'
    testImplementation 'org.jetbrains.kotlin:kotlin-stdlib:2.1.10'
    testImplementation 'com.google.truth:truth:1.1.5'
    testImplementation 'androidx.test:core:1.5.0'
    testImplementation 'org.mockito:mockito-core:5.5.0'
    testImplementation 'org.robolectric:robolectric:4.9'
    testImplementation 'androidx.core:core-ktx:1.10.0'
    testImplementation 'androidx.test.ext:junit:1.1.5'
    testImplementation 'org.mockito.kotlin:mockito-kotlin:5.1.0'
    testImplementation project(':adaptertestkit')
}

/**
 * Jar task to make a sources jar.
 */
task sourcesJar (type: Jar) {
    archiveClassifier = 'sources'
    from android.sourceSets.main.java.srcDirs
}

/**
 * Publish closure consisting of maven publications.
 */
publishing {
    publications {
        adapterPublications(MavenPublication) {
            groupId = stringGroupId
            artifactId = project.name
            version = stringVersion

            // Add the aar artifact to publication.
            artifact("$buildDir/outputs/aar/${project.name}-release.aar") {
                builtBy build
            }

            // Add the sources jar artifact to the publication.
            artifact(sourcesJar)

            // Generate the pom file.
            pom {
                name = "${adapterName} mediation adapter for the Google Mobile Ads SDK"
                description = "The ${adapterName} mediation adapter is a library that handles " +
                        "communication between the Google Mobile Ads SDK and the ${adapterName} " +
                        "SDK. It enables you to load ads from ${adapterName} using the mediation " +
                        "feature in the Google Mobile Ads SDK."
                url = "https://developers.google.com/admob/android/mediation/${project.name}"
                licenses {
                    license {
                        name = 'Apache-2.0'
                        url = 'https://github.com/googleads/googleads-mobile-android-mediation/blob/main/LICENSE'
                        distribution = 'repo'
                    }
                }
            }

            // Add the required dependencies to the generated `pom.xml` file.
            pom.withXml {
                final dependenciesNode = asNode().appendNode('dependencies')
                configurations.implementation.allDependencies.each {
                    // Exclude filetree dependencies.
                    if (it.name != 'unspecified') {
                        println("Adding dependency: " + it.group + ":" + it.name + ":" + it.version)

                        final dependencyNode = dependenciesNode.appendNode('dependency')
                        dependencyNode.appendNode('groupId', it.group)
                        dependencyNode.appendNode('artifactId', it.name)
                        dependencyNode.appendNode('version', it.version)
                        if (it.artifacts.size() > 0) {
                            dependencyNode.appendNode('type', it.artifacts[0].type)
                        }
                    }
                }
            }
        }
    }
}

/**
 * Copy artifacts into a single directory for redistribution.
 */
task copyArtifactsForDistribution(type: Copy) {
    from "$buildDir/outputs/aar/${project.name}-release.aar",
            "$buildDir/libs/${project.name}-sources.jar",
            "$buildDir/publications/adapterPublications/pom-default.xml"
    into "$buildDir/distribution"
}

/**
 * Create `zip` file for redistribution under `build/distribution` directory.
 */
task packageDistribution(type: Zip) {
    from("$buildDir/distribution") {
        rename("${project.name}-release.aar", "${project.name}-${stringVersion}.aar")
        rename("${project.name}-sources.jar", "${project.name}-${stringVersion}-sources.jar")
        rename("pom-default.xml", "${project.name}-${stringVersion}.pom")
    }

    archiveFileName = "${adapterName}AndroidAdapter-${stringVersion}.zip"
    destinationDirectory = file("${rootProject.projectDir}/build/distribution")
}

build.dependsOn clean
build.mustRunAfter clean
copyArtifactsForDistribution.dependsOn(build, sourcesJar, generatePomFileForAdapterPublicationsPublication)
packageDistribution.dependsOn copyArtifactsForDistribution
