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

import java.util.Date;
import java.util.TimeZone;
import java.io.File;
import java.text.SimpleDateFormat


public class SCMQuietPeriod extends SCMChangelog {

    //**************************************************************************
    // CLASS
    //**************************************************************************

    //**************************************************************************
    // INSTANCE
    //**************************************************************************
    
    String remoteUrl
    String remoteUser
    String remotePass
    String repoBaseUrl
    
    /**
     *
     * @return date of the last change
     */
    public def execute() {
        
        if (!directory.list() || directory.list().length == 0) {
            SCMCheckout co = new SCMCheckout()
            
            co.hgCmd = hgCmd
            co.directory = directory
            co.clean = false
            co.remoteUrl = hgHelper.calculateRepositoryUrl(repoBaseUrl, remoteUrl)
            co.remoteUser = remoteUser
            co.remotePass = remotePass
            co.branch = branch
            co.date = startDate
            
            co.execute()
        }
        
        // the result change set date
        Date latestChangeDate = null;
        
        final def cmdHelper = new CommandHelper(this.directory);
        
        // do limited changelog
        def logCommand = [hgCmd, "log"]
        if (branch) {
            logCommand << "--branch" << branch
        }
        logCommand << "-d" <<  hgHelper.formatDateRange(startDate, endDate)
        logCommand << "--template" << "{date|isodate}\\n"
        logCommand << "--limit" << "1"
        logCommand << "--exclude" << ".hgtags" // don not want to check hgtags in quiet period

        cmdHelper.runCommand('Get Mercurial Latest Revision', logCommand){ proc ->
            proc.outputStream.close() // close stdin
            proc.consumeProcessErrorStream(out)
            latestChangeDate = dateParser.parseDate(proc.text.trim())
            println latestChangeDate
        }

        return latestChangeDate;
    }
}
