/**
 * 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.plugin.docker

import com.urbancode.air.CommandHelper
import com.urbancode.air.ExitCodeException

class OpenShiftClient {

    private static CommandHelper ch = new CommandHelper(new File('.'))
    private static String script = 'oc'

    /**
    *  @param proc The process to retrieve the standard output and standard error from
    *  @return An array containing the standard output and standard error of the process
    */
    private static String[] captureCommand(Process proc) {
        StringBuffer stdOut = new StringBuffer()
        StringBuffer stdErr = new StringBuffer()
        proc.waitForProcessOutput(stdOut, stdErr)
        proc.out.close()
        return [stdOut.toString(), stdErr.toString()]
    }

    /**
    *  @param message The message to output before running the command
    *  @param arguments An ArrayList of oc arguments to be executed by the command prompt
    *  @param closure The closure to interact with the Process IO
    */
    private static void runCommand(String message, ArrayList args, Closure closure) {
        args.add(0, script)
        ch.runCommand(message, args, closure)
    }

    /**
    *  @param projectName The name of the project to switch to
    */
    public static void switchToProject(String projectName) {
        def args = []
        args << 'project'
        args << projectName
        try {
            runCommand("[Action] Switching to OpenShift project ${projectName}...", args) { Process proc ->
                def (String sout, String serr) = captureCommand(proc)
                if (serr) {
                    println (serr)
                    println (sout)
                    println ('[Error] Could not switch projects.')
                }
                else {
                    println (sout)
                    println ('[Ok] Switched projects.')
                }
            }
        }
        catch (IOException e) {
            println ("[Error] Could not switch projects: ${e.getMessage()}")
        }
        catch (ExitCodeException e) {
            println ("[Error] Could not switch projects: ${e.getMessage()}")
        }
    }

    /**
    *  @param imagestream The name of the imagestreamstream to get labels for
    *  @return A hashmap of label name, value pairs, or an empty HashMap for any failures
    */
    public static HashMap<String,String> getLabels(String imagestream) {
        HashMap<String,String> labels = new HashMap<String,String>()
        def args = []
        args << 'describe'
        args << 'is'
        args << imagestream
        try {
            runCommand("[Action] Getting Labels for imagestream ${imagestream}...", args) { Process proc ->
                def (String sout, String serr) = captureCommand(proc)
                if (serr) {
                    println (serr)
                    println (sout)
                    println ('[Error] Could not get Labels.')
                }
                else {
                    def labelsLine = false
                    sout.split('\n').each { line ->
                        if (labelsLine && !line.startsWith('\t')) {  // lines containing Label key=value pairs has ended
                            labelsLine = false
                        }
                        if (line.startsWith('Labels:')) {  // lines containing Label key=value pairs has started
                            labelsLine = true
                        }

                        if (labelsLine) {  // line contains Label key=value pair
                            def keyValuePair = line.substring(line.lastIndexOf('\t') + 1).split('=')
                            if (keyValuePair.size() == 2) {
                                println ("[Ok] Found Label: ${keyValuePair[0]}=${keyValuePair[1]}")
                                labels.put(keyValuePair[0], keyValuePair[1])
                            }
                            else {
                                println ("[Error] Bad Label value discarded: ${keyValuePair}")
                            }
                        }
                    }
                }
            }
        }
        catch (IOException e) {
            println ("[Error] Could not get labels: ${e.getMessage()}")
        }
        catch (ExitCodeException e) {
            println ("[Error] Could not get labels: ${e.getMessage()}")
        }
        finally {
            if (labels.size() > 0) {
                println ("[Ok] Found ${labels.size()} OpenShift imagestream Labels, will be set as version properties for each tag.")
            }
            else {
                println ("[Ok] No OpenShift imagestream Labels found.")
            }
            return labels
        }
    }
}
