apply from: "$rootDir/Script/FrameworkConfig.gradle"

gradle.projectsEvaluated {
    def libraryExtension = getExtensions().findByName("android")
    if (libraryExtension == null) {
        return
    }

    // 获取aidl源码路径
    // TODO 这里没有区分debug还是release,可能会有问题,遇到问题再修改
    def aidlSrcDirs = new HashSet<String>()
    for (sourceSets in libraryExtension.sourceSets) {
        def aidl = sourceSets.aidl
        if (aidl.name.contains("android test") || aidl.name.contains("test ")) {
            continue
        }
        aidlSrcDirs.addAll(aidl.srcDirs)
    }

    // 拼接aidl编译参数
    // -I DIR, --include=DIR
    // 指定依赖的aidl目录
    String aidlInclude = ""
    for (String dir : aidlSrcDirs) {
        aidlInclude += "-I$dir "
    }
    aidlInclude = aidlInclude.trim()

    // 获取编译aidl的Task,一般是compileDebugAidl和compileReleaseAidl
    def aidlCompile = new HashSet<Task>()
    for (task in tasks.collect()) {
        def taskName = task.name
        if (taskName.contains("AndroidTest")) {
            continue
        }
        if (taskName.toLowerCase().contains("aidl")) {
            aidlCompile.add(task)
        }
    }

    def frameworksAidl = "$frameworkAidlPath"
    if (frameworksAidl == null || frameworksAidl.isBlank()) {
        println("frameworksAidl is null")
        return
    }
    for (aidlTask in aidlCompile) {
        aidlTask.doFirst { task ->
            def buildTools = task.buildTools
            def aidlExecutable = buildTools.aidlExecutableProvider().get()
            def aidlFrameworkProvider = buildTools.aidlFrameworkProvider().get()

            def aidlSourceOutputDir = null
            for (File file : task.getOutputs().files.files) {
                if (file.absolutePath.contains("aidl_source_output_dir")) {
                    aidlSourceOutputDir = file
                }
            }

            for (File file : task.getInputs().files.files) {
                if (file.isDirectory()) {
                    continue
                }
                if (file.name == "framework.aidl") {
                    continue
                }
                // aidl编译命令
                // -p FILE, --preprocessed=FILE
                //          Include FILE which is created by --preprocess.
                // -d FILE, --dep=FILE
                //          Generate dependency file as FILE. Don't use this when
                //          there are multiple input files. Use -a then.
                // -o DIR, --out=DIR    aidl编译生成的Java文件所在目录
                String cmd = String.format("%s -p%s -I%s %s -o%s %s", aidlExecutable,
                        aidlFrameworkProvider, frameworksAidl, aidlInclude, aidlSourceOutputDir, file)
                runtimeExec(cmd)
            }

            // 结束自带的aidl编译Task
            throw new StopExecutionException()
        }
    }
}