import groovy.json.JsonSlurper

import java.nio.file.Paths

ext.getAppPath = { userDir ->
    def relativePathToApp = "app"
    def nsConfigFile = file("$userDir/nsconfig.json")
    def nsConfig

    if (project.hasProperty("appPath")) {
        // when appPath is passed through -PappPath=/path/to/app
        // the path could be relative or absolute - either case will work
        relativePathToApp = appPath
    } else if (nsConfigFile.exists()) {
        nsConfig = new JsonSlurper().parseText(nsConfigFile.getText("UTF-8"))
    }

    if (nsConfig != null && nsConfig.appPath != null) {
        relativePathToApp = nsConfig.appPath
    }

    return Paths.get(userDir).resolve(relativePathToApp).toAbsolutePath()
}

ext.getAppResourcesPath = { userDir ->
    def relativePathToAppResources
    def absolutePathToAppResources
    def nsConfigFile = file("$userDir/nsconfig.json")
    def nsConfig

    if (nsConfigFile.exists()) {
        nsConfig = new JsonSlurper().parseText(nsConfigFile.getText("UTF-8"))
    }

    if (project.hasProperty("appResourcesPath")) {
        // when appResourcesPath is passed through -PappResourcesPath=/path/to/App_Resources
        // the path could be relative or absolute - either case will work
        relativePathToAppResources = ext.appResourcesPath
        absolutePathToAppResources = Paths.get(userDir).resolve(relativePathToAppResources).toAbsolutePath()
    } else if (nsConfig != null && nsConfig.appResourcesPath != null) {
        relativePathToAppResources = nsConfig.appResourcesPath
        absolutePathToAppResources = Paths.get(userDir).resolve(relativePathToAppResources).toAbsolutePath()
    } else {
        absolutePathToAppResources = "${getAppPath(userDir)}/App_Resources"
    }

    return absolutePathToAppResources
}