import com.urbancode.air.*
import com.urbancode.air.plugin.automation.*

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

final def workDir = new File('.').canonicalFile
def stepProps = apTool.getStepProperties()
def dir = new File(workDir, stepProps['workDirOffset'] ?: '.').canonicalFile

def serverUrl = stepProps['serverUrl']
def username = stepProps['username']
def password = stepProps['password'] ? stepProps['password'] : stepProps['passwordscript']
def domain = stepProps['qcdomain']
def project = stepProps['qcproject']
def failmode = stepProps['failmode']
def matchCriteria = stepProps['matchcriteria']?.split('\n') as List
def returnFields = stepProps['returnfields']?.split('\n') as List

if (!matchCriteria) {
    println "No query terms inputed!"
}
else if (!returnFields) {
    println "No return fields inputed! No data will be returned"
}
else {
    def processedCriteria = ""
    def processedFields = ""
    
    for (criteria in matchCriteria) {
        if (criteria.trim().size() > 0) {
            def criterion = criteria.split("=", 2)
            if (criterion.size() < 2) {
                println "Invalid criteria " + criteria;
            }
            else {
                processedCriteria += criterion[0].trim() + ","
                processedCriteria += criterion[1].trim().replace("\"", "__QUOTE")
                processedCriteria += "|"
            }
        }
    }
    processedCriteria = processedCriteria[0..-2]
    
    for (returnField in returnFields) {
        if (returnField.trim().size() > 0) {
            if (processedFields.size() > 0) {
                processedFields += ","
            }
            processedFields += returnField.trim()
        }
    }
    
    QCQuery create = new QCQuery()
    create.serverUrl = serverUrl
    create.username = username
    create.password = password
    create.domain = domain
    create.project = project
    
    create.matchCriteria = processedCriteria
    create.returnFields = processedFields
    
    create.workDir = dir
    
    create.execute()
}

System.exit(0);