import groovy.json.JsonSlurper

/**
 * 在 config.json 中 根据 appConfig 和 pkgConfig 来 include 本地模块
 */
def config = new JsonSlurper().parse(file("./config.json"))

for (def pro in config.proConfig) {
    String localPath = pro.localPath

    if (localPath == ":feature:mock") {
        if (config.pkgConfig.isEmpty()) {
            pro.isApply = false
        }
    } else if (localPath.endsWith(":app")) {
        def appName = localPath.substring(":feature:".length(), localPath.length() - 4)
        if (!config.appConfig.contains(appName)) {
            pro.isApply = false
        }
    } else if (localPath.endsWith(":pkg")) {
        if (!config.pkgConfig.isEmpty()) {
            def pkgName = localPath.substring(":feature:".length(), localPath.length() - 4)
            if (!config.pkgConfig.contains(pkgName)) {
                pro.isApply = false
            }
        }
    }

    if (pro.useLocal && pro.isApply) {
        def projectPath = ":" + localPath.substring(1).replace(":", "_")
        include projectPath
        project(projectPath).projectDir = file(localPath.substring(1).replace(":", "/"))
    }
}

def ls = System.getProperty("line.separator")

List<String> proDeps = []
for (def pro in config.proConfig) {
    boolean useLocal = pro.useLocal
    String localPath = pro.localPath
    String remotePath = pro.remotePath
    String name = localPath.replace(":", "_").replace("-", "_").substring(1)
    if (localPath != null) localPath = "\"$localPath\""
    if (remotePath != null) remotePath = "\"$remotePath\""
    boolean isApply = pro.isApply
    proDeps.add(String.format("%-12s%-27s: new DepConfig(%-5s, %-5s, $localPath%s),",
            "", name, isApply, useLocal, remotePath == null ? "" : ", $remotePath"))
}

def configFile = file('./buildSrc/src/main/groovy/Config.groovy')
def lines = configFile.readLines("utf8")
def configContent = new StringBuilder()

boolean enterNeverFlag = false
for (def line : lines) {
    if (enterNeverFlag) {
        if (line.contains("/*Never")) {
            configContent.append(ls).append(line)
            enterNeverFlag = false
        }
        continue
    }
    configContent.append(ls).append(line)
    if (line.contains("/*Never")) {
        configContent.append(ls).append(String.format("%-12s/*Generated by \"config.json\"*/", ""))
        enterNeverFlag = true
        for (String dep : proDeps) {
            configContent.append(ls).append(dep)
        }
    }
}
configFile.write(configContent.substring(ls.length()).toString())