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
    String detectedIn
    String reproducible
    String subject
    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)
        }
        if (detectedOn) {
            additionalFields.setProperty("Field('BG_DETECTION_DATE')", detectedOn)
        }
        if (detectedIn) {
            additionalFields.setProperty("Field('BG_DETECTION_VERSION')", detectedIn)
        }
        if (reproducible) {
            additionalFields.setProperty("Field('BG_REPRODUCIBLE')", reproducible)
        }
        if (subject) {
            additionalFields.setProperty("Field('BG_SUBJECT')", subject)
        }
    }
    
    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)
    }
}