package com.atlassian.bitbucket.pull;

import com.atlassian.bitbucket.util.PageRequest;
import org.apache.commons.lang3.StringUtils;

import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.util.Locale;

/**
 * Specifies the direction a list of results should be ordered - oldest first or newest first.
 *
 * @see PullRequestSearchRequest#getOrder()
 */
public enum PullRequestOrder {

    /** Indicates older pull requests should be shown before newer ones */
    OLDEST,
    /** Indicates newer pull requests should be shown before older ones */
    NEWEST,
    /**
     * Indicates pull requests should be shown in an order based on {@link PullRequestParticipantStatus status}.
     * For PRs where the participant has the same status {@link PullRequestOrder#NEWEST NEWEST} order will be applied
     *
     * @see {@link PullRequestService#search(PullRequestSearchRequest, PageRequest)} for more information on restrictions
     * @since 4.4
     **/
    PARTICIPANT_STATUS;

    /**
     * Coerces a string to a {@link PullRequestOrder} or returns the supplied default value if this is not possible.
     *
     * @param stringValue the string value of the pull request
     * @param defaultValue the default value to return if coercion is not possible
     * @return the corresponding {@link PullRequestOrder} instance
     */
    public static PullRequestOrder fromString(@Nullable String stringValue, @Nullable PullRequestOrder defaultValue) {
        try {
            return valueOf(StringUtils.upperCase(stringValue, Locale.ROOT));
        } catch (IllegalArgumentException | NullPointerException ignored) {
            // Fall-through intentional
        }

        return defaultValue;
    }

    /**
     * @return {@link #NEWEST}
     */
    @Nonnull
    public static PullRequestOrder getDefaultOrder() {
        return PullRequestOrder.NEWEST;
    }
}
