package com.urbancode.air.plugin.scm

import java.text.*;
import java.util.Date;


public class SCMHelper {

    static public final String MERCURIAL_DATE_FORMAT = "yyyy-MM-dd HH:mm:ss";

    //final static public String DATE_PATTERN = "yyyy-MM-dd HH:mm Z";

    public def getDateFormatter() {
        return new SimpleDateFormat(MERCURIAL_DATE_FORMAT)
    }

    public String formatDate(Date date) {
        return !date ? null : getDateFormatter().format(date);
    }

    public String formatDateRange(Date since, Date until) {
        def f = this.getDateFormatter();
        if (since && until) {
            return "${f.format(since)} to ${f.format(until)}"
        }
        else if (!since && !until) {
            return null
        }
        else if (!since && until) {
            return "<${f.format(until)}"
        }
        else if (since && !until) {
            return ">${f.format(since)}"
        }
        else {
            // assuming dates are not mutated asynchronously with this
            // we can't get here, prior 4 blocks cover all possibilities
            throw IllegalStateException("Can not format $since .. $until range")
        }
    }

    /**
     * Calculate a Mercurial repository URL given a
     * @param prefix a uri String used for resolving relative paths (can be null)
     * @param path an absolute or relative uri String for the repository (should never be null)
     * @return the combined + normalized url (never null)
     */
    public String calculateRepositoryUrl(String prefix, String path) {
        def pathURI = new URI(path);
        def result = pathURI;
        if (prefix) {
            def prefixURI = new URI(prefix+"/");
            result = prefixURI.resolve(path);
        }
        return result.normalize().toString();
    }
}