import groovy.xml.XmlUtil

apply plugin: 'com.android.application'

gradle.projectsEvaluated {
    tasks.withType(JavaCompile) {
        options.compilerArgs.add('-Xbootclasspath/p:libs/framework-stub.jar')
    }
}

android {
    compileSdkVersion 28
    buildToolsVersion '28.0.3'

    defaultConfig {
        multiDexEnabled false
        minSdkVersion 23
    }

    sourceSets {
        main {
            java.srcDirs += ['src/main/apacheCommonsLang']
            jniLibs.srcDirs = ['libs']
        }
    }

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

    // Only build the release variant
//    variantFilter { variant ->
//        if (variant.buildType.name != BuilderConstants.DEBUG) {
//            variant.ignore = true
//        }
//    }
}

task generateStubs(type: Javadoc, dependsOn: 'compileReleaseSources') {
    source = file('src/main/java')
    ext.stubsDir = "$buildDir/api/stub-sources"
    outputs.dir ext.stubsDir
    title = null

    options {
        doclet = 'com.google.doclava.Doclava'
        docletpath = fileTree(dir: 'doclib', include: '**/*.jar').asType(List)
        jFlags '-Dignore.symbol.file'
        addBooleanOption 'nodocs', true
        addFileOption 'stubs', file(ext.stubsDir)
        addFileOption 'api', file('doclib/api/current.txt')
        addBooleanOption 'hide 111', true
        addBooleanOption 'hide 113', true
        addBooleanOption 'hidePackage xposed.dummy', true
    }
}

task compileStubs(type: JavaCompile, dependsOn: 'generateStubs') {
    source = fileTree(generateStubs.ext.stubsDir)
    destinationDir = file("$buildDir/api/stub-classes")
    options.compilerArgs += '-XDsuppressNotes'
}

task jarStubs(type: Jar) {
    from compileStubs
    destinationDir = file("$buildDir/api")
    baseName = 'api'
}

task jarStubsSource(type: Jar) {
    from generateStubs.source
    destinationDir = jarStubs.destinationDir
    baseName = jarStubs.baseName
    classifier = 'sources'
}

task generateAPI(dependsOn: ['generateStubs', 'jarStubs', 'jarStubsSource'])

// Make sure that hiddenapistubs are placed before the Android SDK in app.iml
// as there doesn't seem to be any way to configure this in Android Studio.
task fixIml {
    ext.imlFile = projectDir.absolutePath + '/' + project.name + '.iml'
    inputs.file imlFile
    outputs.file imlFile

    println imlFile
    doLast {
        def imlFile = file(project.name + ".iml")
        println 'Change ' + project.name + '.iml order'
        try {
            def parsedXml = (new XmlParser()).parse(imlFile)
            def jdkNode = parsedXml.component[1].orderEntry.find { it.'@type' == 'jdk' }
            parsedXml.component[1].remove(jdkNode)
            def sdkString = "Android API " + android.compileSdkVersion.substring("android-".length()) + " Platform"
            new Node(parsedXml.component[1], 'orderEntry', ['type': 'jdk', 'jdkName': sdkString, 'jdkType': 'Android SDK'])
            XmlUtil.serialize(parsedXml, new FileOutputStream(imlFile))
        } catch (FileNotFoundException e) {
            // nop, iml not found
        }
    }
}

tasks.preBuild.dependsOn fixIml

dependencies {
    compileOnly files("libs/framework-stub.jar")
    compileOnly project(':dexmaker')
}

afterEvaluate {

    task javac

    tasks.withType(JavaCompile) {
        options.compilerArgs.add('-Xbootclasspath/p:libs/framework-stub.jar')
    }

    android.applicationVariants.all { variant ->
        def nameCapped = variant.name.capitalize()
        def nameLowered = variant.name.toLowerCase()

        def makeAndCopyTask = task("makeAndCopy${nameCapped}", type: Copy, dependsOn: "assemble${nameCapped}") {
            from "build/intermediates/transforms/dexMerger/${nameLowered}/0/classes.dex"
            into '../Core/template_override/system/framework'
            rename("classes.dex", "edxposed.dex")
        }

//        def makeAndCopyTask = task("makeAndCopy${nameCapped}", type: Jar, dependsOn: "assemble${nameCapped}") {
//            from "build/intermediates/transforms/dexMerger/${nameLowered}/0/"
//            destinationDir file("../Core/template_override/system/framework/")
//            baseName "edxposed"
//        }
    }

}