/*
 * Licensed Materials - Property of IBM Corp.
 * IBM UrbanCode Deploy
 * (c) Copyright IBM Corporation 2016. All Rights Reserved.
 *
 * U.S. Government Users Restricted Rights - Use, duplication or disclosure restricted by
 * GSA ADP Schedule Contract with IBM Corp.
 */

package com.urbancode.air.plugins.autoscaler

import groovy.json.JsonSlurper
import com.urbancode.air.CommandHelper

public class CloudFoundry {

    def bearerToken// Token used to login to BlueMix/CF Servers

    CloudFoundry() {
        this.bearerToken = getCFBearerToken()
    }
    /**
     * @return Returns the bearerToken if it exists, else crashes. The bearerToken is required to run any CF command.
     */
    public static def getCFBearerToken() {
        def result
        def jsonFile = new File (System.getProperty("user.home") + "${File.separator}.cf${File.separator}config.json")
        JsonSlurper slurper = new JsonSlurper()
        def configInfo = slurper.parseText(jsonFile.text)
        result = configInfo.AccessToken
        if (!result) {
            println "[Error] Bearer Token is empty or not found."
            println "[Error] Token is searched for in: ${System.getProperty('user.home')}${File.separator}.cf${File.separator}config.json."
            println "[Possible Solution] Login by using the IBM Container's Login Step or through 'cf login' on the command line."
            System.exit(1)
        }
        return result
    }

    /**
     * @param input The Application's name or ID.
     * @return      Tries to find the Application's ID. If the command fails, it assumes the given
     *              input is an ID.
     */
    public static def getAppId(def input) {
        def result
        final def workDir = new File('.').canonicalFile
        def ch = new CommandHelper(workDir)
        ch.ignoreExitValue(true)
        def args =["cf", "app", input, "--guid"]
        ch.runCommand("[Action] Discovering if the App ID is needed...", args, getChOutput)

        // Parse System Output
        if (chOutput.contains("FAILED")){
            println "[Ok] '$input' is recognized as an Application ID."
            result = input
        }
        else {
            println "[Ok] '$input' is recognized as an Application Name."
            result = chOutput.trim()
        }
        return result
    }

    // Closure to get the output from CLI
    static def chOutput = ""
    public static def getChOutput = {Process proc ->
        def out = new PrintStream(System.out, true)
        def outputStream = new StringBuilder()
        try {
            proc.waitForProcessOutput(outputStream, out)
        }
        finally {
            out.flush();
        }
        chOutput = outputStream.toString()
    }
}