package com.urbancode.air.plugin.scm

import com.urbancode.air.plugin.scm.changelog.ChangeSet
import java.text.SimpleDateFormat

public class SCMQuietPeriod extends SCMChangelog {
    
    def dateParser = null
    def startDate = null
    
    public def execute() {
        def latestDate = getLatestChangeDate()
        return latestDate
    }
    
    public def getLatestChangeDate() {
        if (stream && !snapshot && !baseline) {
            def startSnapshot
            def snapshotList = getStreamSnapshots()
            for (i in 0..snapshotList.size()) {
                if (snapshotList[i].date.before(startDate)) {
                    startSnapshot = snapshotList[i].alias
                    break
                }
            }
            if (!startSnapshot) {
                println "Could not locate a previous snapshot on stream ${stream} that was created before ${startDate}."
                println "Assuming there are no changes!"
            }
            else {
                def componentSet
                if (components) {
                    componentSet = components.split(',')
                }
                def changelogText = getChangelog(startSnapshot, 'snapshot', stream, 'stream', componentSet)
                parseChangelog(changelogText)
                 
                return changeSets.collect{ ChangeSet cs -> cs.date }.max();
            }
        }
        else if (snapshot || baseline) {
            println "Building from snapshot or baseline so no need for quiet period!"
        }
        else {
            println "No stream specified!"
        }
    }
    
    public def getStreamSnapshots() {
        def snapshotText
        def result = []
        def dateFormat = new SimpleDateFormat(listSnapshotDateFormat)
        getCmdHelper().runCommand('List stream snapshots', [command, '--non-interactive', 'list', 'snapshots',
                stream,
                '-u', username,
                '-P', password,
                '-r', serverUrl]) {proc ->
            proc.consumeProcessErrorStream(System.out)
            proc.outputStream.close()
            snapshotText = proc.text.trim()
            println snapshotText
        }
        snapshotText.eachLine {it ->
            def line = it.trim()
            line.find('\\((\\d+)\\) "(.+)" (.*)') {match, alias, name, date ->
                result << [alias:alias, date:dateFormat.parse(date)]
            }
        }
        return result
    }
}