package com.atlassian.stash.sal.api.lifecycle;

import org.springframework.core.OrderComparator;
import org.springframework.core.Ordered;

/**
 * @since 2.9
 */
public class LifecycleAwareComparator extends OrderComparator {

    /**
     * The default order applied to {@code LifecycleAware} components which do not explicitly implement {@code Ordered}.
     */
    private static final int DEFAULT_ORDER = 5;

    /**
     * Overrides the default Spring implementation to return {@link #DEFAULT_ORDER} for objects that don't implement
     * {@code Ordered}. Spring's default ({@code Ordered#LOWEST_PRECEDENCE}) is {@code Integer.MAX_VALUE}, which leaves
     * no room for ordering components after it.
     *
     * @param obj the object to retrieve execution order for
     * @return the execution order for the provided object
     */
    @Override
    protected int getOrder(Object obj) {
        return obj instanceof Ordered ? ((Ordered) obj).getOrder() : DEFAULT_ORDER;
    }
}
