import java.security.MessageDigest

apply plugin: 'com.android.library'
apply from: "../maven.gradle"

android {

    compileSdkVersion rootProject.ext.compileSdkVersion

    buildTypes {
        release {
            minifyEnabled false
//            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), '../proguard-base.pro'
//            consumerProguardFiles 'proguard-custom.pro'
        }
    }
    compileOptions {
        sourceCompatibility rootProject.ext.sourceJavaVersion
        targetCompatibility rootProject.ext.targetJavaVersion
    }
    lintOptions {
        checkReleaseBuilds false
        abortOnError false
    }
    defaultConfig {
        minSdkVersion rootProject.ext.minSdkVersion
        targetSdkVersion rootProject.ext.targetSdkVersion
    }
}

dependencies {
    api project(':analysys_core')
    api project(':analysys_encryption')
    api project(':analysys_push')
    api project(':analysys_visual')
    api project(':analysys_allgro')
}

task delRelease(type: Delete) {
    delete('../release')
    delete('../../../repo')

//    delete('../../repo/cn/com/analysys/analysys-core/')
//    delete('../../repo/cn/com/analysys/analysys-encrypt/')
//    delete('../../repo/cn/com/analysys/analysys-push/')
//    delete('../../repo/cn/com/analysys/analysys-visual/')
//    delete('../../repo/cn/com/analysys/analysys-allgro/')
//    delete('../../repo/cn/com/analysys/analysys-arkanalysys/')
}

task releaseAar(type: Copy) {

    for (int i = 0; i < moduleName.size; i++) {
        def tmpName = "${moduleName[i]}".replace("_${rootProject.ext.version}", "")

        def endName = "${moduleName[i]}".replaceAll("_", "-")
        from("../${tmpName}/build/outputs/aar/") {
            rename("${tmpName}-release.aar", "${endName}.aar")
            exclude("${tmpName}-release.aar.asc")
        }
    }

    includeEmptyDirs = false

    into '../release/aar/'

}

task releaseMapping(type: Copy, dependsOn: ['releaseAar']) {

    for (int i = 0; i < moduleName.size; i++) {

        def tmpName = "${moduleName[i]}".replace("_${rootProject.ext.version}", "")

        def endName = "${moduleName[i]}".replaceAll("_", "-")
        from("../${tmpName}/build/outputs/mapping/release/") {
            include('mapping.txt')
            rename('mapping.txt', "mapping-${endName}.txt")
        }
    }

    into '../release/mapping/'
}

task zipMapping(type: Zip, dependsOn: ['releaseMapping']) {
    from '../release/mapping/'

    archiveName = "analysys_pass_android_${version}_mapping_${releaseTimeVariable}.zip"
    destinationDir file("../release/zip")
}


for (int i = 0; i < moduleName.size(); i++) {
    def endName = "${moduleName[i]}".replaceAll("_", "-")

    task "unZipAAR${moduleName[i]}"(type: Copy) {
        from(zipTree("../release/aar/${endName}.aar"))
        into "../release/jar/${endName}"
    }

    task "unZipClasses${moduleName[i]}"(type: Copy, dependsOn: ["unZipAAR${moduleName[i]}"]) {
        from(zipTree("../release/jar/${endName}/classes.jar"))
        into "../release/jar/${endName}/classes/"
    }

    task "unZipJar${moduleName[i]}"(type: Copy, dependsOn: ["unZipClasses${moduleName[i]}"]) {
        from("../release/jar/${endName}/classes/")
        from("../release/jar/${endName}") {
            include('assets/')
        }
        into "../release/jar/tmp/${endName}/"

        includeEmptyDirs = false
    }


    task "jar${moduleName[i]}"(type: Jar, dependsOn: ["unZipJar${moduleName[i]}"]) {
        from("../release/jar/tmp/${endName}/")
        println("endName:" + endName)
        baseName = "${endName}".replace("-${rootProject.ext.version}", "")
        destinationDir = file("../release/jar/")


        manifest {
            attributes(
                    'Implementation-Title': "${project.name}",
                    'Implementation-Version': "${rootProject.ext.version}",
                    'Built-Date': new Date().getDateTimeString(),
                    'Built-With': "gradle-${project.getGradle().getGradleVersion()},groovy-${GroovySystem.getVersion()}",
                    'Created-By': 'Java ' + System.getProperty('java.version') + ' (' + System.getProperty('java.vendor') + ')')
        }
    }

    task "jarclean${moduleName[i]}"(type: Delete, dependsOn: ["jar${moduleName[i]}"]) {

        delete("../release/jar/${endName}")
        delete("../release/jar/tmp")
    }
}

task makeJar() {

}

for (int i = 0; i < moduleName.size(); i++) {
    makeJar.dependsOn "jarclean${moduleName[i]}"
}

task makeDemo(type: Copy) {
    from("../../ans-demo/") {
        include("apidemo/src/")
        include("apidemo/proguard-rules.pro")
    }
    from("../../projectBuildTools/")

    into("../release/zip/demo")
}

task makeDemoAar(type: Copy, dependsOn: ["makeDemo"]) {
    from("../release/aar/")

    into("../release/zip/demo/apidemo/libs")
}

task makeZipAns(type: Zip, dependsOn: ["makeDemoAar"]) {

    from("../release/zip/demo/")
//    from("../release/") {
//        include("aar/")
//        include("jar/")
//        exclude("jar/analysys-allgro-*")
//
//    }

//    from("../../") {
//        include("repo/")
//    }

    archiveName = "analysys_pass_android_${version}_Demo_${releaseTimeVariable}.zip"
    destinationDir file("../release/zip")

}

task makeZipAAR(type: Zip) {
    from("../release/") {
        include("aar/")
        include("jar/")
        exclude("jar/analysys-allgro-*")
    }

    archiveName = "analysys_pass_android_${version}_SDK_${releaseTimeVariable}.zip"
    destinationDir file("../release/zip")
}

task makeMd5() {
    doLast {
        File dir = file("../release/aar")
        File[] list = dir.listFiles()
        StringBuilder sbMd5 = new StringBuilder("文件md5\n\n")
        for (File file : list) {
            sbMd5.append(file.getName()).append(":").append(generateMD5(file)).append("\n");
        }
        File md5File = file("../release/aar/readme.md")
        md5File.createNewFile()
        md5File.text = sbMd5.toString()

        dir = file("../release/jar")
        list = dir.listFiles()
        sbMd5 = new StringBuilder("文件md5\n\n")
        for (File file : list) {
            sbMd5.append(file.getName()).append(":").append(generateMD5(file)).append("\n");
        }
        md5File = file("../release/jar/readme.md")
        md5File.createNewFile()
        md5File.text = sbMd5.toString()
    }
}

task makeZipAnsClean(type: Delete, dependsOn: ["makeZipAns", "makeMd5", "makeZipAAR"]) {
    delete("../release/zip/demo/")
    delete("../release/aar/")
    delete("../release/jar/")
}

static def generateMD5(file)
{
    MessageDigest md = MessageDigest.getInstance("MD5");
    file.eachByte 4096, {bytes, size ->
        md.update(bytes, 0, size);
    }
    return md.digest().collect {String.format "%02x", it}.join()
}