package com.atlassian.stash.internal.commit.graph.cache;

import java.util.Comparator;

/**
 * A {@link Comparator} to sort {@link AbstractCacheTraversalJob}s in reverse priority order. This accepts all
 * {@link Runnable}s, treating all non-job {@code Runnable}s as being the lowest priority.
 *
 * @since 2.11
 */
public class CacheTraversalJobComparator implements Comparator<Runnable> {

    @Override
    public int compare(Runnable o1, Runnable o2) {
        boolean o1IsCacheTraversalJob = o1 instanceof AbstractCacheTraversalJob;
        boolean o2IsCacheTraversalJob = o2 instanceof AbstractCacheTraversalJob;
        if (o1IsCacheTraversalJob && o2IsCacheTraversalJob) {
            return ((AbstractCacheTraversalJob) o2).getPriority() - ((AbstractCacheTraversalJob) o1).getPriority();
        } else if (o1IsCacheTraversalJob) {
            return -1;
        } else if (o2IsCacheTraversalJob) {
            return 1;
        }
        // else all non CacheTraversalJobs are the same to us
        return 0;
    }
}
