/*
* 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.
*/
    
//
// desination url components
//

if (createBranch && !createBranch.startsWith('${')) {
    // VALIDATE createBranch contains only legal characters
}

if (createTag && !createTag.startsWith('${')) {
    // VALIDATE createTag contains only legal characters
}

if (createBranch && createTag) {
    if (!createBranch.startsWith('${') || !createTag.startsWith('${')) {
      errors.createBranch = 'Can not specify both branch and tag'
      errors.createTag    = 'Can not specify both branch and tag'
    }
}
    
if (!createTag && !createBranch) {
    errors.createBranch = 'Must specify either branch or tag to create'
    errors.createTag    = 'Must specify either branch or tag to create'
}
    
//
// source url components
//

if (fromBranch && fromTag) {
    if (!fromBranch.startsWith('${') || !fromTag.startsWith('${')) {
      errors.fromBranch = 'Can not specify both a branch and a tag to label'
      errors.fromTag = 'Can not specify both a branch and a tag to label'
    }
}
    
if (revision && !revision.startsWith('${')) {
    // validate revision is a number
    if (!revision.isLong()) {
        errors.revision = 'Revision must be a whole number'
    }
}

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 (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'
    }
}