package com.urbancode.build.plugin.ucd.rest
/*
 * Licensed Materials - Property of HCL
 * UrbanCode Build
 * (c) Copyright HCL Technologies Ltd. 2019. All Rights Reserved.
 */
import com.urbancode.air.ExitCodeException
import org.codehaus.jettison.json.JSONObject

class AppProcessRequest {
    String application
    String applicationProcess
    String environment
    String snapshot
    String description
    boolean onlyChanged
    Map<String, List<String>> versions
    Map<String, String> properties

    public AppProcessRequest(Properties props) {
        String component = props['componentName']?.trim()
        String version = props['versionName']?.trim()

        /* Differentiate between snapshot deployment and version deployment */
        if (component && version) {
            application = props['applicationName']?.trim()
            environment = props['environmentName']?.trim()
            versions = new HashMap<String, List<String>>()
            versions.put(component, [version])
            properties = parseProperties(props['propertiesTextArea']?.trim())
        }
        else {
            application = props['application']?.trim()
            environment = props['environment']?.trim()
            snapshot = props['snapshot']?.trim()
            properties = parseProperties(props['properties']?.trim())
        }


        applicationProcess = props['applicationProcess']?.trim()
        description = props['description']?.trim()
        onlyChanged = Boolean.valueOf(props['onlyChanged'])
    }

    /*
     * Get a string representation of the application process request.
     */
    public String toString() {
        String procString = "application=${application}, " +
            "applicationProcess=${applicationProcess}, environment=${environment}, " +
            "description=${description}, onlyChange=${onlyChanged}, properties=${properties}"

        if (snapshot) {
            procString += ",snapshot=${snapshot}"
        }
        else {
            procString += ",versions=${versions}"
        }

        return procString
    }

    /**
     * Parse through newline separated list of property names and values delimited by '/'
     * @param unparsedProps
     */
    private Map<String, String> parseProperties(String unparsedProps) {
        Map<String, String> propMap = new HashMap<String, String>()

        for (String property : unparsedProps.tokenize("\n")) {
            List<String> splitProp = property.tokenize("/")

            if (splitProp.size() > 1) {
                String propName = splitProp.get(0)
                String propValue = splitProp.get(1)

                propMap.put(propName, propValue)
            }
        }

        return propMap
    }
}
