/*
* 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.
*/
import java.text.*

import com.urbancode.air.*

final def dateParser = new DateParser();
final def apTool = new AirPluginTool(this.args[0], this.args[1])

final String PERL_FILE_PREFIX   = "clearquest-defect-details";
final String PERL_FILE_SUFFIX   = ".pl";

//------------------------------------------------------------------------------
// PARSE PROPERTIES
//------------------------------------------------------------------------------
final def stepProps = apTool.getStepProperties()
final def workDir = new File('.').canonicalFile

// Automation
final String serverName = stepProps['automation']
final String username = stepProps['automation/username'] ?: ''
final String password = stepProps['automation/password'] ?: stepProps['automation/passwordScript']
final String dbName = stepProps['automation/dbName']
final String schema = stepProps['automation/schema']
final String commandPath = stepProps['automation/commandPath'] ?: 'CQperl.exe'

// Step
final def headline = stepProps['headline']
final def severity = stepProps['severity']
final def project = stepProps['projectName']
final def priority = stepProps['priority']
final def owner = stepProps['owner']
final def description = stepProps['defectDescription']

if (headline == null) {
    throw new IllegalStateException('Headline is required');
}
if (severity == null) {
    throw new IllegalStateException('Severity is required');
}

final String script = """
        use CQPerlExt;
        \$CQSession = CQPerlExt::CQSession_Build();
        \$CQSession->UserLogon('${username}', \$ARGV[0], '${dbName}', '${schema}');
        \$entity = \$CQSession->BuildEntity("defect");
        \$entity->SetFieldValue("Headline", "${headline}");
        \$entity->SetFieldValue("severity", "${severity}");
        if (description != null && description.trim().length() > 0) {
                    \$entity->SetFieldValue("description", "${description}");
        }
        if (project != null && project.trim().length() > 0) {
                    \$entity->SetFieldValue("project", "${project}");
        }
        if (priority != null && priority.trim().length() > 0) {
                    \$entity->SetFieldValue("priority", "${priority}");
        }
        if (owner != null && owner.trim().length() > 0) {
                    \$entity->SetFieldValue("owner", "${owner}");
        }
        \$status = \$entity->Validate();
        print \$status;
        if (\$status == ""){
                \$entity->Commit();
        }
        else {
                \$entity->Revert();
        }
        CQSession::Unbuild(\$CQSession);
"""

File cmdFile = File.createTempFile(PERL_FILE_PREFIX, PERL_FILE_SUFFIX);
FileOutputStream fos = new FileOutputStream(cmdFile, true);
Writer writer = new BufferedWriter(new OutputStreamWriter(fos, "US-ASCII"));

try {
    writer.write(script);
}
finally {
    writer.close();
}

//------------------------------------------------------------------------------
// PREPARE COMMAND LINE
//------------------------------------------------------------------------------

String[] commandLine = new String[3];
commandLine[0] = commandPath
commandLine[1] = cmdFile.getCanonicalPath()
commandLine[2] = password

//------------------------------------------------------------------------------
// EXECUTE CQ UPDATE
//------------------------------------------------------------------------------

if (!workDir.exists()) {
  workDir.mkdirs();
}

CommandHelper cmdHelper = new CommandHelper(workDir);

println "ClearQuest command line: " + commandPath + " " + cmdFile.getCanonicalPath()
println "ClearQuest command working Directory: " + workDir.getCanonicalPath()
println "ClearQuest command environment: "

cmdHelper.runCommand('', commandLine);