/*
* Licensed Materials - Property of IBM* and/or HCL**
* UrbanCode Deploy
* UrbanCode Build
* UrbanCode Release
* AnthillPro
* (c) Copyright IBM Corporation 2011, 2017. All Rights Reserved.
* (c) Copyright HCL Technologies Ltd. 2018. All Rights Reserved.
*
* U.S. Government Users Restricted Rights - Use, duplication or disclosure restricted by
* GSA ADP Schedule Contract with IBM Corp.
*
* * Trademark of International Business Machines
* ** Trademark of HCL Technologies Limited
*/

import org.codehaus.jettison.json.JSONArray

import java.nio.charset.Charset

import com.urbancode.air.AirPluginTool
import com.urbancode.ub.client.ProcessClient

AirPluginTool airTool = new AirPluginTool(args[0], args[1])
Properties props = airTool.getStepProperties()
def workDir = new File('.').canonicalFile

def fileName = props['fileName']
def overwrite = props['overwrite']?.toBoolean()
def versionCriteria = props['versionCriteria']


def url = System.getenv("WEB_URL")
def projectId = System.getenv("PROJECT_ID")
def workflowId = System.getenv("WORKFLOW_ID")
def username = airTool.getAuthTokenUsername()
def authToken = System.getenv("AUTH_TOKEN")
def requestId = System.getenv("REQUEST_ID")

def processClient = new ProcessClient(new URI(url), username, authToken, true)

JSONArray response = processClient.getDependencyProcesses(projectId, workflowId, true)
String processRequestSource = processClient.getProcessRequestSource(requestId)

try {
    Charset encodingToUse = null;
    Charset defaultEncoding = Charset.forName(System.getenv("DS_SYSTEM_ENCODING"));
    encodingToUse = defaultEncoding;


    File file = new File(fileName).getCanonicalFile();
    if (file.exists() && !overwrite) {
        println "File $file already exists!"
        System.exit 1
    }
    else {
        println "Using file encoding " + encodingToUse.name()

        OutputStreamWriter outputStreamWriter = new OutputStreamWriter(new FileOutputStream(file, true), encodingToUse);

        boolean modified = false
        if (response != null && response.length() > 0) {
            for (int i = 0; i < response.length(); i++) {
                def dependency = response.getJSONObject(i)

                String dependencyProjectId = dependency.optString("projectId", null)
                String dependencyWorkflowId = dependency.optString("workflowId", null)
                String buildProfileName = dependency.optString("buildProfileName", "UNKNOWN")
                String projectName = dependency.optString("projectName", "UNKNOWN")
                String key = projectName.replaceAll("[^a-zA-Z0-9]", "")

                if (dependencyProjectId == null || dependencyWorkflowId == null) {
                    println "Skipping invalid dependency entry: ${dependency}\n"
                    continue
                }

                try {
                    def latestBuild = processClient.getLatestBuildLife(dependencyProjectId, dependencyWorkflowId)

                    String value
                    if ('stamp'.equals(versionCriteria)) {
                        value = latestBuild.optString("stamp", "N/A")
                    } else { // buildLifeId (default)
                        value = latestBuild.optString("id", "N/A")
                    }

                    if (processRequestSource != null && projectName.equals(processRequestSource)) {
                        println "Checking for payload property for Requester: ${processRequestSource}"
                        String payload = null

                        def propsArray = latestBuild.optJSONArray("properties")
                        if (propsArray != null) {
                            for (int j = 0; j < propsArray.length(); j++) {
                                def prop = propsArray.getJSONObject(j)
                                if ("payload".equals(prop.optString("name"))) {
                                    payload = prop.optString("value")
                                    break
                                }
                            }
                        }

                        if(payload != null) {
                            println "Payload found and set as buildlife property"
                            airTool.setOutputProperty("buildlife/payload", payload)
                        }
                        else {
                            println "Payload not found."
                        }
                    }

                    outputStreamWriter.write("${key}=${value}\n")
                    airTool.setOutputProperty("buildlife/${projectName}.version", value)
                    airTool.setOutputProperties()



                    modified = true
                } catch (Exception e) {
                    println "Failed to fetch latest buildLife for projectId=${dependencyProjectId}, workflowId=${dependencyWorkflowId}"
                }
            }
        } else {
            println "No dependency processes found"
        }

        outputStreamWriter.close()
        airTool.storeOutputProperties()

        if (!modified)
            println "No build data found to write"
        else
            println "Successfully created/modified file $file with the content"
    }
}
catch (Exception e) {
    println "Error creating file $fileName: ${e.message}"
    System.exit(1)
}

System.exit(0)
