/*
* 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.text.SimpleDateFormat


public class SCMQuietPeriod extends SCMChangelog {

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

    //**************************************************************************
    // INSTANCE
    //**************************************************************************

    /**
     *
     * @return date of the last change
     */
    public def execute() {
        // quiet period needs to init workspace
        initWorkspace();

        def logOutput = runLogCommand()
        List<ChangeSet> changeSets = parseLogIntoChangeSets(logOutput);
        Date latestChangeDate = changeSets.collect{ChangeSet cs -> cs.date}.max();
        return latestChangeDate;
    }
    
    protected String runLogCommand() {
        // we want  a trailing separator from the change sets
        // use unit-separator %x1F in format string, null (%x00) breaks output on msysgit
        // %B is preferred as it doesn't reformat the commit messages, but %s%n%b will have to suffice
        def format;

        if (useEmail) {
            format = ['%H', '%ae', '%at', '%s%n%b', ''].join(UNIT_SEPARATOR_FMT)
        }
        else {
            format = ['%H', '%an', '%at', '%s%n%b', ''].join(UNIT_SEPARATOR_FMT)
        }

        def logCommand = [scmCommand, '--no-pager', 'log', '-z', '--no-renames', '--name-status', "--format=format:$format"]
        String startPoint = startRevision ?: lookupRevision(startDate);
        String endPoint = endRevision ?: lookupRevision(endDate);

        // QP should use Dates, CL uses revisions
        if (startPoint || endPoint) {
            def range = "${startPoint ?: ''}..${endPoint ?: 'HEAD'}"
            logCommand << range
        }

        logCommand << "$remoteName/$branch";
        logCommand << '--'

        def logOutput = getCommandText(logCommand);
        return logOutput.replaceFirst('\0$', ''); // trim the dangling null
    }
}