package com.urbancode.air.plugin.scm

import java.text.SimpleDateFormat

public class SCMQuietPeriod extends SCMChangelog {
    
    public def execute() {
        def latestDate = getLatestChangeDate()
        return latestDate
    }
    
    public def getLatestChangeDate() {
        if (stream && !snapshot && !baseline) {
            def startSnapshot
            def snapshotList = rtcHelper.getStreamSnapshots()
            for (i in 0..snapshotList.size()) {
                if (snapshotList[i].date.getTime() < startTime) {
                    startSnapshot = snapshotList[i].alias
                    break
                }
            }
            if (!startSnapshot) {
                println "Could not locate a previous snapshot on stream ${stream} that was created before ${new Date(startTime)}."
                println "Assuming there are no changes!"
            }
            else {
                def componentSet
                if (components) {
                    componentSet = components.split(',')
                }
                getChangelog(startSnapshot, 'snapshot', stream, 'stream', componentSet)
                
                def latestDate
                def dateFormat = new SimpleDateFormat(CHANGELOG_DATE_FORMAT)
                filteredChangeSets.each{ change ->
                    def time = dateFormat.parse(change.date)?.getTime()
                    if (time > latestDate && time > startTime) {
                        latestDate = time
                    }
                }
                
                return latestDate
            }
        }
        else if (snapshot || baseline) {
            println "Building from snapshot or baseline so no need for quiet period!"
        }
        else {
            println "No stream specified!"
        }
    }
}