import com.urbancode.air.*
import com.urbancode.air.plugin.scm.*
import java.text.*
import groovy.xml.XmlUtil;

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

//------------------------------------------------------------------------------
// PARSE PROPERTIES
//------------------------------------------------------------------------------

final def stepProps = apTool.getStepProperties()
final def workDir = new File('.').canonicalFile


final String clearToolCommand = stepProps['source/repo/commandPath'] ?: 'cleartool'

final String srcName    = stepProps['source'];
final File dir          = new File(workDir, stepProps['source/dirOffset'] ?: '.').canonicalFile // get checkout directory
final String streamName = stepProps['source/streamName']
final String strategy          = stepProps['source/strategy']
final String loadRules  = stepProps['source/loadRules']
final String viewName   = stepProps['source/viewName']
final String viewPath   = stepProps['source/viewPath']

def userExcludesString  = stepProps['source/excludeUsers'] ?: ''
def fileFiltersString   = stepProps['source/fileFilters'] ?: '';

final def startRevision = stepProps['startRevision'] ?: ''
final def endRevision   = stepProps['endRevision'] ?: ''
final def startDate     = dateParser.parseDate(stepProps['startDate']) // explicit start date ?: startBuildLife.actualWorkspaceDate
final def endDate       = dateParser.parseDate(stepProps['endDate'])   // explicit end date ?: buildLife.actualWorkspaceDate

// create the directory ahead of time
dir.mkdirs()

// Execute
SCMQuietPeriod quietPeriod = new SCMQuietPeriod()
quietPeriod.scmCommand = clearToolCommand
quietPeriod.directory = dir
quietPeriod.streamName = streamName
quietPeriod.strategy = strategy
quietPeriod.startRevision = startRevision
quietPeriod.endRevision = endRevision
quietPeriod.startDate = startDate
quietPeriod.endDate = endDate
quietPeriod.loadRules = loadRules
quietPeriod.viewName = viewName
quietPeriod.viewPath = viewPath

quietPeriod.userExcludes = userExcludesString
quietPeriod.fileFilters = fileFiltersString

Date latestRevisionDate = quietPeriod.execute()

//------------------------------------------------------------------------------
// UPLOAD LATEST CHANGE DATE
//------------------------------------------------------------------------------
if (latestRevisionDate == null) {
    println('No changes detected')
}
else {
    apTool.setOutputProperty("job/latest.change.time.${srcName}", String.valueOf(latestRevisionDate.time))
    apTool.storeOutputProperties()
    println "Latest Revision Date: " + latestRevisionDate
}
