import groovy.json.JsonSlurper

static def isWindows() {
    System.properties['os.name'].toLowerCase().contains('windows')
}

def execCommand(command) {
    def cmdLine = isWindows() ? ["cmd", "/c", command] : command
    logger.quiet("Build Config Command: $command")

    def process = cmdLine.execute()
    def (out, err) = new StringWriter().with {
        o -> new StringWriter().with {
            e -> process.waitForProcessOutput(o, e)
                [o,e]*.toString()
        }
    }

    logger.quiet("Build Config exitValue: ${process.exitValue()}")

    if (process.exitValue() != 0) {
        logger.error("Failed to get build config for $command: $err")
        return
    }
    logger.quiet(out)

    return out
}

def determineBuildConfigName() {
    if (project.hasProperty('BUILD_CONFIG_NAME')) {
        return project.BUILD_CONFIG_NAME
    } else if (System.getenv()["BUILD_CONFIG_NAME"]) {
        return System.getenv()['BUILD_CONFIG_NAME']
    } else {
        logger.warn("WARNING: No build config specified. Using the build config 'integreat'!")
        return 'integreat'
    }
}

def createYarnProcess(buildConfigName, platform, command) {
    return execCommand("yarn --silent app-toolbelt v0 build-config $command $buildConfigName $platform")
}

def createBuildConfig(buildConfigName) {
    logger.quiet("Using build config $buildConfigName")

    def proc = createYarnProcess(buildConfigName, "android", "to-json")
    def buildConfig = new JsonSlurper().parseText(proc)
    return buildConfig
}

def setupGoogleServices(buildConfig, resValue) {
    def gs = buildConfig.googleServices

    if (gs == null) {
        logger.warn("WARNING: Google Services are not used in this build!")
        return
    }

    resValue("string", "google_app_id", gs.googleAppId)
    resValue("string", "gcm_defaultSenderId", gs.gcmDefaultSenderId)
    resValue("string", "default_web_client_id", gs.defaultWebClientId)
    if (gs.ga_trackingId != null) {
        resValue("string", "ga_trackingId", gs.gaTrackingId)
    }
    resValue("string", "firebase_database_url", gs.firebaseDatabaseUrl)
    resValue("string", "google_api_key", gs.googleApiKey)
    resValue("string", "google_crash_reporting_api_key", gs.googleCrashReportingApiKey)
    resValue("string", "project_id", gs.projectId)
}

def setupResourceValues(buildConfigName, resValue) {
    logger.quiet("Using build config $buildConfigName")

    def proc = createYarnProcess(buildConfigName, "android", "to-properties")
    def buildConfigProperties = new Properties()
    buildConfigProperties.load(new StringReader(proc))

    // Java properties use the same syntax as xcconfig files
    // https://docs.oracle.com/javase/7/docs/api/java/util/Properties.html
    buildConfigProperties.each {
        def escaped = it.value.replaceAll("%", "\\\\u0025")
        // Make build config values available as string resource, e.g. for use in AndroidManifest
        resValue "string", it.key, "\"$escaped\""
    }
}


def determineIcon(buildConfig) {
    return [icon: "${buildConfig.appIcon}", notificationIcon: "${buildConfig.notificationIcon}"]
}

ext {
    determineBuildConfigName = this.&determineBuildConfigName
    createBuildConfig = this.&createBuildConfig
    setupGoogleServices = this.&setupGoogleServices
    setupResourceValues = this.&setupResourceValues
    determineIcon = this.&determineIcon
}
