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

final def DATE_READ_1 = new java.text.SimpleDateFormat("E MMM dd HH:mm:ss zzz yyyy") // java.util.Date.toString()
final def DATE_READ_2 = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss z") // ISO-like format

if (fromBranch && fromTag) {
    if (!fromBranch.startsWith('${') || !fromTag.startsWith('${')) {
      // neither appears dynamic, not allowed
      errors.fromBranch = 'Can not specify both a branch and a tag to check out from'
      errors.fromTag = 'Can not specify both a branch and a tag to check out from'
    }
}
    
if (revision && !revision.startsWith('${')) {
    // validate revision is a number
    if (!revision.isLong()) {
        errors.revision = 'Revision must be a whole number'
    }
}

if (date && !date.startsWith('${')) {
    boolean valid = false
    // validate date format
    
    if (date.isLong()) {
        // is milliseconds since epoch, valid
        valid = true;
    } else {
        [DATE_READ_1, DATE_READ_2].each{format ->
            try {
                format.parse(date)
                valid = true
            }
            catch (java.text.ParseException e) {
                // not a match for this format
            }
        }
    }
    
    if (!valid) {
        errors.date = 'Date is not a valid format'
    }
}

if (revision && date) {
    if (!revision.startsWith('${') || !date.startsWith('${')) {
        // revisionand date are both present and non-dynamic
        errors.revision = 'Revision and Date can not both be specified'
        errors.date = 'Revision and Date can not both be specified'
    }
}