plugins {
    id 'com.microsoft.identity.buildsystem' version '0.2.5'
    id 'com.android.library'
    id 'pmd'
    id 'checkstyle'
    id 'maven-publish'
}

apply from: 'versioning/version_tasks.gradle'

buildSystem {
    desugar = false
}

group = 'com.microsoft.aad'

configurations {
    javadocDeps
}

configurations.all {
    resolutionStrategy.cacheChangingModulesFor 0, 'seconds'
}

allprojects {
    repositories {
        mavenLocal()
        google()
        maven {
            name "vsts-maven-adal-android"
            url "https://identitydivision.pkgs.visualstudio.com/_packaging/AndroidADAL/maven/v1"
            credentials {
                username System.getenv("ENV_VSTS_MVN_ANDROIDADAL_USERNAME") != null ? System.getenv("ENV_VSTS_MVN_ANDROIDADAL_USERNAME") : project.findProperty("vstsUsername")
                password System.getenv("ENV_VSTS_MVN_ANDROIDADAL_ACCESSTOKEN") != null ? System.getenv("ENV_VSTS_MVN_ANDROIDADAL_ACCESSTOKEN") : project.findProperty("vstsMavenAccessToken")
            }
        }
        mavenCentral()
    }
}
android {
    namespace "com.microsoft.aad.adal"
    compileOptions {
        // Sets Java compatibility to Java 8
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
    buildFeatures {
        buildConfig = true
    }

    compileSdk rootProject.ext.compileSdkVersion

    defaultConfig {
        multiDexEnabled true
        minSdkVersion rootProject.ext.minSdkVersion
        targetSdkVersion rootProject.ext.targetSdkVersion
        versionCode getAppVersionCode()
        versionName getAppVersionName()
        project.archivesBaseName = "adal"
        project.version = android.defaultConfig.versionName
        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }
    publishing {
        multipleVariants {
            withJavadocJar()
            withSourcesJar()
        }
    }
    buildTypes {
        debug {
            testCoverageEnabled false
            debuggable true
            buildConfigField("String", "VERSION_NAME", "\"${project.version}\"")
        }
        release {
            minifyEnabled false
            debuggable false
            proguardFiles getDefaultProguardFile('proguard-android.txt')
            buildConfigField("String", "VERSION_NAME", "\"${project.version}\"")
        }
    }

    flavorDimensions "main"

    productFlavors {
        // The 'local' productFlavor sources common from mavenLocal and is intended to be used
        // during development.
        local {
            dimension "main"
            versionNameSuffix "-local"
        }

        snapshot {
            dimension "main"
        }

        // The 'dist' productFlavor sources common from a central repository and is intended
        // to be used for releases.
        dist {
            dimension "main"
        }
    }

    sourceSets {
        main {
            manifest.srcFile 'src/main/AndroidManifest.xml'
            java.srcDirs = ['src/main/java', 'src/main/aidl', 'src/telemetry/java', 'src/third_party/java']
        }

        androidTest.setRoot('src/androidTest')
    }

    lintOptions {
        abortOnError true
        disable 'MissingPermission'
        disable 'LongLogTag'
        disable 'DefaultLocale'
        disable 'UnusedResources'
        disable 'GradleDependency'
        disable 'GradleOverrides'
        disable 'OldTargetApi'
        disable 'PackageManagerGetSignatures'
    }

    libraryVariants.all { variant ->
        variant.outputs.all {
            outputFileName = "${archivesBaseName}-${version}.aar"
        }
    }

    useLibrary 'android.test.mock'
}

// In dev, we want to keep the dependencies(common4j, broker4j, common) to 1.0.+ to be able to be consumed by daily dev pipeline.
def commonVersion = "1.0.+"
if (project.hasProperty("distCommonVersion")) {
    commonVersion = project.distCommonVersion
}
dependencies {
    // Dependencies
    implementation "androidx.appcompat:appcompat:$rootProject.ext.appCompatVersion"
    implementation "com.google.code.gson:gson:$rootProject.ext.gsonVersion"
    implementation "androidx.annotation:annotation:$rootProject.ext.annotationVersion"
    implementation "androidx.legacy:legacy-support-v4:$rootProject.ext.legacySupportV4Version"
    implementation "com.nimbusds:nimbus-jose-jwt:$rootProject.ext.nimbusVersion"
    implementation "androidx.constraintlayout:constraintlayout:$rootProject.ext.constraintLayoutVersion"

    // 'local' flavor dependencies
    localApi(project(":common")) {
        transitive = true
    }

    snapshotApi(group: 'com.microsoft.identity', name: 'common', version: commonVersion, changing: true)

    // 'dist' flavor dependencies
    distApi("com.microsoft.identity:common:${commonVersion}") {
        transitive = true
    }

    // Android Instrumented Test Dependencies
    androidTestImplementation "androidx.test.ext:junit:$rootProject.ext.androidxJunitVersion"
    androidTestImplementation "androidx.test:runner:$rootProject.ext.runnerVersion"
    androidTestImplementation "androidx.test:rules:$rootProject.ext.rulesVersion"
    androidTestImplementation "org.mockito:mockito-android:$rootProject.ext.mockitoAndroidVersion"

    // Test Dependencies
    testImplementation "junit:junit:$rootProject.ext.junitVersion"
    testImplementation "org.mockito:mockito-core:$rootProject.ext.mockitoCoreVersion"
    testImplementation ("org.robolectric:robolectric:$rootProject.ext.robolectricVersion")
    testImplementation "androidx.test:core:$rootProject.ext.androidxTestCoreVersion"
    testLocalImplementation project(':testutils')
    testDistImplementation("com.microsoft.identity:testutils:0.0.+") {
        exclude module: 'common'
        exclude group: 'com.microsoft.identity', module: 'LabApiUtilities'
    }

    // Javadoc Dependencies
    javadocDeps "androidx.annotation:annotation:$rootProject.ext.annotationVersion"
    javadocDeps "androidx.legacy:legacy-support-v4:$rootProject.ext.legacySupportV4Version"
}

task sourcesJar(type: Jar) {
    from android.sourceSets.main.java.srcDirs
    archiveClassifier.set('sources')
    destinationDirectory = reporting.file("$project.buildDir/outputs/jar/")
}

task javadoc(type: Javadoc) {
    failOnError false
    source = android.sourceSets.main.java.srcDirs
    configurations.implementation.setCanBeResolved(true)
    classpath += configurations.implementation
    classpath += project.files(android.getBootClasspath().join(File.pathSeparator))
    classpath += configurations.javadocDeps
    exclude '**/*.aidl'

    if (JavaVersion.current().isJava8Compatible()) {
        allprojects {
            tasks.withType(Javadoc) {
                options.addStringOption('Xdoclint:none', '-quiet')
            }
        }
    }

    destinationDir = reporting.file("$project.buildDir/outputs/jar/javadoc/")
}

tasks.register('javadocJar', Jar) {
    dependsOn javadoc
    archiveClassifier.set('javadoc')
    from javadoc.destinationDir
    destinationDirectory = reporting.file("$project.buildDir/outputs/jar/")
}

// For publishing to the remote maven repo.
afterEvaluate{
    publishing {
        publications {
            distRelease(MavenPublication) {
                from components.findByName('distRelease')
                groupId 'com.microsoft.aad'
                artifactId 'adal'
                //Edit the 'version' here for VSTS RC build
                version = project.version
                pom {
                    name = 'adal'
                    description = 'Azure active directory library for Android gives you the ability to add Windows Azure Active Directory authentication to your application with just a few lines of additional code. Using our ADAL SDKs you can quickly and easily extend your existing application to all the employees that use Windows Azure AD and Active Directory on-premises using Active Directory Federation Services, including Office365 customers.'
                    url = 'https://github.com/AzureAD/azure-activedirectory-library-for-android'
                    developers {
                        developer {
                            id = 'microsoft'
                            name = 'Microsoft'
                        }
                    }
                    licenses {
                        license {
                            name = 'MIT License'
                        }
                    }
                    inceptionYear = '2014'
                    scm {
                        url = 'https://github.com/AzureAD/azure-activedirectory-library-for-android/tree/master'
                    }
                    properties = [
                            branch : 'master',
                            version: project.version
                    ]
                }
            }
        }

    // Repositories to which Gradle can publish artifacts
        repositories {
            maven {
                name "vsts-maven-adal-android"
                url "https://identitydivision.pkgs.visualstudio.com/_packaging/AndroidADAL/maven/v1"
                credentials {
                    username System.getenv("ENV_VSTS_MVN_ANDROIDADAL_USERNAME") != null ? System.getenv("ENV_VSTS_MVN_ANDROIDADAL_USERNAME") : project.findProperty("vstsUsername")
                    password System.getenv("ENV_VSTS_MVN_ANDROIDADAL_ACCESSTOKEN") != null ? System.getenv("ENV_VSTS_MVN_ANDROIDADAL_ACCESSTOKEN") : project.findProperty("vstsMavenAccessToken")
                }
            }
        }
    }
}

// Repositories from which Gradle can fetch dependencies
repositories {
    maven {
        name "vsts-maven-adal-android"
        url "https://identitydivision.pkgs.visualstudio.com/_packaging/AndroidADAL/maven/v1"
        credentials {
            username System.getenv("ENV_VSTS_MVN_ANDROIDADAL_USERNAME") != null ? System.getenv("ENV_VSTS_MVN_ANDROIDADAL_USERNAME") : project.findProperty("vstsUsername")
            password System.getenv("ENV_VSTS_MVN_ANDROIDADAL_ACCESSTOKEN") != null ? System.getenv("ENV_VSTS_MVN_ANDROIDADAL_ACCESSTOKEN") : project.findProperty("vstsMavenAccessToken")
        }
    }
}

def getTimestamp() {
    def date = new Date()
    return date.format('yyyyMMdd.HHmm')
}

artifacts {
    archives javadocJar
    archives sourcesJar
}

pmd {
    ignoreFailures = false
    reportsDir = file("$project.buildDir/outputs/")
}

tasks.register('pmd', Pmd) {
    description 'Run pmd'
    group 'verification'

    ruleSets = ["java-basic", "java-braces", "java-strings", "java-unusedcode"]
    source = fileTree('src/main/java')

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

    }
}

def configDir = new File(buildscript.sourceFile.parentFile.parentFile, 'config')
ext.checkstyleConfigDir = "$configDir/checkstyle"

checkstyle {
    ignoreFailures = false
    reportsDir = file("$project.buildDir/outputs/")
}

tasks.register('checkstyle', Checkstyle) {
    configFile file("${project.rootDir}/config/checkstyle/checkstyle.xml")

    configProperties.checkstyleConfigDir = checkstyleConfigDir
    configProperties.checkstyleSuppressionsPath = file("${project.rootDir}/config/checkstyle/suppressions.xml").absolutePath
    source 'src'
    include '**/*.java'
    exclude '**/gen/**'
    classpath = files()
}

tasks.configureEach { task ->
    if (task.name == 'assembleDebug' || task.name == 'assembleRelease') {
        task.dependsOn 'checkstyle', 'pmd', 'lint'
    }
}

