package com.atlassian.bitbucket.mesh.git.builder.revlist;

import com.atlassian.bitbucket.mesh.rpc.v1.RpcRevListOrder;

import javax.annotation.Nonnull;
import javax.annotation.Nullable;

import static java.util.Objects.requireNonNull;

/**
 * Enumerates the possible orders for {@code git rev-list}, controlling use of the {@code --date-order}
 * and {@code --topo-order} flags.
 */
public enum GitRevListOrder {

    /**
     * Similar to {@link #DATE --date-order}, except commits are ordered by the author timestamp instead of the
     * commit timestamp.
     */
    AUTHOR_DATE("--author-date-order"),
    /**
     * Similar to {@link #TOPOLOGICAL --topo-order} in the sense that no parent comes before all of its children,
     * but otherwise things are still ordered in the commit timestamp order.
     */
    DATE("--date-order"),
    /**
     * Apply {@code git rev-list}'s default behaviour.
     */
    DEFAULT,
    /**
     * Output the commits in topological order (i.e. descendant commits are shown before their parents).
     */
    TOPOLOGICAL("--topo-order");

    private final String flag;

    GitRevListOrder() {
        flag = null;
    }

    GitRevListOrder(String flag) {
        this.flag = flag;
    }

    @Nonnull
    public static GitRevListOrder fromRpc(@Nonnull RpcRevListOrder rpc) {
        switch (requireNonNull(rpc, "rpc")) {
            case ORDER_AUTHOR_DATE:
                return AUTHOR_DATE;
            case ORDER_DATE:
                return DATE;
            case ORDER_TOPOLOGICAL:
                return TOPOLOGICAL;
            default:
                return DEFAULT;
        }
    }

    @Nullable
    public String getFlag() {
        return flag;
    }

    public boolean isFlagged() {
        return flag != null;
    }
}
