package com.atlassian.bitbucket.repository;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.annotation.Nullable;

/**
 * Defines orderings which can be applied when retrieving references. The actual approach for applying an ordering is
 * not established or guaranteed by this enumeration; it may vary by SCM implementation or {@link Ref} type.
 */
public enum RefOrder {

    /**
     * Return references in <i>ascending</i> alphabetical order.
     */
    ALPHABETICAL,
    /**
     * Return references in <i>descending</i> modification order, with the most recently-modified references returned
     * first.
     */
    MODIFICATION;

    private static final Logger log = LoggerFactory.getLogger(RefOrder.class);

    /**
     * Parses the provided {@code order}, <i>if possible</i>. If the {@code order} provided is {@code null}, empty
     * or does not match a known order, {@code null} is returned.
     * 
     * @param order the order to parse
     * @return the parsed order, or {@code null} if it cannot be parsed
     */
    @Nullable
    public static RefOrder fromValueOrNull(@Nullable String order) {
        RefOrder value = null;
        if (StringUtils.isNotBlank(order)) {
            try {
                value = valueOf(StringUtils.upperCase(order));
            } catch (IllegalArgumentException ignored) {
                log.warn("Defaulting unknown order [{}] to {}", order, value);
            }
        }
        return value;
    }
}
