/*
* 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.
*/
package com.urbancode.air.plugin.scm

import com.urbancode.air.CommandHelper

import java.text.ParseException
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 snapshotList = getSnapshotList()
            def startSnapshot = snapshotList.find { it.date.before(startDate) }?.name
            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 changelogs = getChangelog(startSnapshot, 'snapshot', stream, 'stream', componentSet)
                parseChangelog(changelogs)
                setAddedDateForChangeSets(stream)

                def latestDate
                componentToChangeSetsMap.each { component, changeSetsMap ->
                    changeSetsMap.each { changeSetId, changeSet ->
                       if (!latestDate) {
                           latestDate = changeSet.date
                       }
                       else if (latestDate.before(changeSet.date)) {
                           latestDate = changeSet.date
                       }
                    }
                }
                return latestDate
            }
        }
        else if (snapshot || baseline) {
            println "Building from snapshot or baseline so no need for quiet period!"
        }
        else {
            println "No stream specified!"
        }
    }

    protected def getSnapshotList() {
        def snapshotText
        def result = []
        def dateFormat = new SimpleDateFormat(listSnapshotDateFormat)
        def listSnapshotsCommand = [command, '-a', 'n', '--non-interactive', 'list', 'snapshots',
                                    workspace ?: stream,
                                    '-u', username,
                                    '-P', password,
                                    '-r', serverUrl]

        CommandHelper cmdHelper = getCmdHelper()
        boolean ignoreExitValue = cmdHelper.ignoreExitValue
        cmdHelper.ignoreExitValue = true
        def exitCode = runCommand('List stream snapshots', listSnapshotsCommand) {
            println it
            snapshotText = it
        }
        cmdHelper.ignoreExitValue = ignoreExitValue
        if (exitCode == 25) {
            // Exit Code 25 means the workspace/stream could not be found. SCMCheckout already contains the logic for
            // creating new workspaces, so call the method
            SCMCheckout checkout = new SCMCheckout()
            checkout.command = command
            checkout.serverUrl = serverUrl
            checkout.username = username
            checkout.password = password
            checkout.snapshot = snapshot
            checkout.stream = stream
            checkout.workspace = workspace
            checkout.createWorkspace()
        }
        else if (exitCode != 0) {
            System.exit(exitCode)
        }

        snapshotText.eachLine {
            try {
                def line = it.trim()
                def firstSpace = line.indexOf(" ")
                def name = stripQuotes(line.substring(0, firstSpace))
                def date = line.substring(firstSpace + 1)
                result << [name: name, date: dateFormat.parse(date)]
            }
            catch (ParseException e) {
                // Swallow exception
            }

        }
        return result
    }
}
