apply plugin: 'com.android.library'

android {
    compileSdkVersion rootProject.ext.compileSdkVersion

    defaultConfig {
        minSdkVersion rootProject.ext.minSdkVersion
        targetSdkVersion rootProject.ext.targetSdkVersion
        versionCode 1
        versionName "1.0"
    }

    lintOptions {
        abortOnError false
    }

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

def toPath(String s){
    if(isWin()){
        return s.replace('/','\\')
    }else {
        return s
    }
}

def isWin(){
    return org.gradle.internal.os.OperatingSystem.current().isWindows()
}

String.metaClass.toPath = { -> toPath(delegate) }

ext{
    debugClassDir=project.buildDir.absolutePath+'/intermediates/javac/debug/compileDebugJavaWithJavac/classes'.toPath()
    commonJar=project.buildDir.absolutePath+'/appopsx-common.jar'.toPath()
    appopsxJar=project.buildDir.absolutePath+'/appopsx.jar'.toPath()
    appopsxOrigJar=project.buildDir.absolutePath+'/appopsx-orig.jar'.toPath()
}

dependencies {
//    compile project(":opsdeps")
    implementation fileTree(include: ['*.jar'], dir: 'libs')
    compileOnly project(":apicompat")
}

build.doLast {
    println("build success,create jar files.")

    //create origin appopsx-orig.jar, need dx opt
    def pkgDir=["com/zzzmode/appopsx/server/","com/zzzmode/appopsx/common/"]
    createJarFile(appopsxOrigJar,pkgDir)

    //create appopsx-common.jar,and copy to project opsxpro
    pkgDir=["com/zzzmode/appopsx/common/"]
    createJarFile(commonJar,pkgDir)

    //dx optimization jar
    jar2dex()
}

def createJarFile(String jar,List pkgDirPath){
    def buildArgs=['-cvf',jar]
    buildArgs.addAll(get_args(debugClassDir,pkgDirPath))
    exec{
        workingDir=debugClassDir
        executable='jar'
        args=buildArgs
    }
    println("create jar ${jar},dir:${pkgDirPath}")
}

def get_args(String path,List pkgPath){

    def ret=[]
    pkgPath.forEach{
        it ->
            def file = file(path + File.separator + it.toPath())
            loadClsFiles(file,ret,path+File.separator)
    }
    return ret
}

def loadClsFiles(File f,List paths,String ignorePrefix){

    File[] files = f.listFiles()
    if(files != null){
        files.each{
            file ->
                if(file.file){
                    if(file.name.endsWith(".class")){
                        paths.add(file.path.replace(ignorePrefix,""))
                    }
                }else{
                    loadClsFiles(file,paths,ignorePrefix)
                }
        }
    }

}

def findSdkHome() {
    def sdkHome = null
    def pFile = project.rootProject.file("local.properties")
    if (pFile.exists()) {
        def myProp = new Properties()
        pFile.withReader {
            r -> myProp.load(r)
        }
        sdkHome = myProp.getProperty("sdk.dir")
    }

    if (sdkHome == null) {
        sdkHome = System.getenv("ANDROID_HOME")
    }

    if(sdkHome?.trim()?.isEmpty()){
        throw new RuntimeException("not found android sdk environment !")
    }
    return sdkHome
}

def jar2dex(){
    //java jar to dex file
    println("------jar2dex------")
    // find sdk home dir.
    def sdkHome = findSdkHome()

    println("android sdk home:${sdkHome}")
    def dxFile=file("${sdkHome}/build-tools/${rootProject.ext.buildToolsVersion}/dx${isWin()?'.bat':''}".toPath())

    if(dxFile.exists()){
        dxFile.setExecutable(true)
    }else {
        throw new RuntimeException("not found dx executable file in path ${dxFile}")
    }

    println("dx binary file:${dxFile}")

    def cmdArgs=['--dex',"--output=$appopsxJar",appopsxOrigJar]


    def libsDir = file("${rootProject.projectDir.absolutePath}/opsxpro/libs")
    def assetsDir = file("${rootProject.projectDir.absolutePath}/opsxpro/src/main/assets")

    libsDir.mkdirs()
    assetsDir.mkdirs()

    exec{
        workingDir=project.buildDir.absolutePath
        executable=dxFile
        args=cmdArgs
    }
    copy {
        from commonJar
        into libsDir
    }
    copy {
        from appopsxJar
        into assetsDir
    }
    println("----jar2dex success,exec end----")
}