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
    //**************************************************************************

    public def execute() {
        def latestChangeDate
        setupWorkDir()
        

        if (fileFilters) {
            fileFilters.readLines().collect{it.trim()}.findAll{it}.each{filter ->
                def pattern = convertToPattern(filter.substring(1))
                if (filter.startsWith('+')) {
                    includeFiles << pattern
                }
                else if (filter.startsWith('-')) {
                    excludeFiles << pattern
                }
                else {
                  // not a valid expression
                }
            }
        }

        try {
            runLogCommand()

            // Parse Change Log for most recent changeset
            latestChangeDate = determineLatestChangeDate()
        }
        catch (ExitCodeException e) {
            println e.getMessage()
            System.exit(1)
        }

        return latestChangeDate
    }

    private def determineLatestChangeDate() {
        Date lastUpdatedTime

        if (!changeSets) {
            System.out.println("No changes detected");
        }
        else {

            changeSets.each { changeSet ->
                if (lastUpdatedTime == null || changeSet['date'].compareTo(lastUpdatedTime) > 0) {
                    lastUpdatedTime = changeSet['date']
                }
            }
        }

        return lastUpdatedTime
    }
}
