/*
 * pins 模块文件夹设置
 */
ext {
    pins = [
            "xlzx",
            "ydl"
    ]
}

import com.android.manifmerger.ManifestMerger2
import com.android.manifmerger.MergingReport
import com.android.manifmerger.XmlDocument
import com.android.utils.ILogger

buildscript {
    repositories {
        jcenter()
        google()
    }
    dependencies {
        classpath "com.android.tools.build:manifest-merger:26.1.1"
    }
}

def logger = new ILogger() {
    @Override
    void error(Throwable t, String msgFormat, Object... args) {

    }

    @Override
    void warning(String msgFormat, Object... args) {

    }

    @Override
    void info(String msgFormat, Object... args) {

    }

    @Override
    void verbose(String msgFormat, Object... args) {

    }
}

/**
 * 合并Manifes文件
 */
def mergeManifest = { ->
    File mainManifestFile = new File("$projectDir/src/main/AndroidManifest.xml")

    ManifestMerger2.MergeType mergeType = ManifestMerger2.MergeType.APPLICATION
    XmlDocument.Type documentType = XmlDocument.Type.MAIN
    ManifestMerger2.Invoker invoker = new ManifestMerger2.Invoker(mainManifestFile, logger, mergeType, documentType)
    pins.each { pinName ->
        File microManifestFile = new File("$projectDir/src/$pinName/AndroidManifest.xml")
        if (microManifestFile.exists()) {
            //合并 AndroidManifest.xml
            invoker.addLibraryManifest(microManifestFile)
        } else {
            //没有 AndroidManifest.xml 不需要合并
        }
    }
    def mergingReport = invoker.merge()
    def moduleAndroidManifest = mergingReport.getMergedDocument(MergingReport.MergedManifestKind.MERGED)

    new File("$buildDir").mkdirs()
    def file = new File("$buildDir/AndroidManifest.xml")
    file.createNewFile()
    file.write(moduleAndroidManifest)
}

/**
 * 创建pins文件夹
 */
task createPinsDirectory {
    pins.each { pinName ->
        if (file("$projectDir/src/${pinName}").exists()) {
            //目录已经存在
        } else {
            //创建目录
            String packageDir = rootProject.ext.android.applicationId.replace(".", "/")
            // 创建java目录
            new File("$projectDir/src/${pinName}/java/" + packageDir).mkdirs()
            // 创建资源文件目录
            new File("$projectDir/src/${pinName}/res").mkdirs()
        }
    }
}

task mergeManifestTask {
    mergeManifest()
}

preBuild.doFirst {
    mergeManifest()
}

preBuild.dependsOn(createPinsDirectory)