/*
* Licensed Materials - Property of IBM Corp.
* IBM UrbanCode Build
* (c) Copyright IBM Corporation 2012, 2014. 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.automation

public class QCCreate extends AutomationBase {
    
    String assignee
    String summary
    String priority
    String status
    String severity
    String qcProjectKey
    String detectedBy
    String detectedOn
    def issuePropsStr
    
    private def additionalFields
    
    public void execute() {
        init()
        generateProperties()
        createDefect()
    }
    
    private void generateProperties() {
        // parse the additional fields into a Properties object
        additionalFields = new Properties()
        if (issuePropsStr != null) {
            try {
                additionalFields.load(new ByteArrayInputStream(issuePropsStr.getBytes()))
            }
            catch (Exception e) {
                throw new Exception("Additional fields formatted incorrectly: " + e.getMessage())
            }
        }
        
        // add the defined fields that can be updated to the Properties object
        if (assignee) {
            additionalFields.setProperty("AssignedTo", assignee)
        }
        if (summary) {
            additionalFields.setProperty("Summary", summary)
        }
        if (priority) {
            additionalFields.setProperty("Priority", priority)
        }
        if (status) {
            additionalFields.setProperty("Status", status)
        }
        if (severity) {
            additionalFields.setProperty("Field('BG_SEVERITY')", severity)
        }
        if (qcProjectKey) {
            additionalFields.setProperty("Project", qcProjectKey)
        }
        if (detectedBy) {
            additionalFields.setProperty("DetectedBy", detectedBy)
        }
    }
    
    private void createDefect() {
        def createCommand = [cscriptExe]
        createCommand << PLUGIN_HOME + "\\qc_create.vbs"
        createCommand << serverUrl
        createCommand << username
        createCommand << password
        createCommand << domain
        createCommand << project

        additionalFields.keySet().each() { additionalFieldName ->
            createCommand << additionalFieldName
            createCommand << additionalFields.getProperty(additionalFieldName)
        }

        runCommand("Creating defect", createCommand)
    }
}