package org.xbib.datastructures.immutable.order;

import java.util.Arrays;
import java.util.Comparator;
import static org.xbib.datastructures.immutable.ImmutableCollection.toArray;

/**
 * An ordering that tries several comparators in order.
 */
final class CompoundOrdering<T> extends Ordering<T> {
    final Comparator<? super T>[] comparators;

    @SuppressWarnings("unchecked")
    CompoundOrdering(Comparator<? super T> primary, Comparator<? super T> secondary) {
        this.comparators = (Comparator<? super T>[]) new Comparator[]{primary, secondary};
    }

    @SuppressWarnings("unchecked")
    CompoundOrdering(Iterable<? extends Comparator<? super T>> comparators) {
        this.comparators = toArray(comparators, new Comparator[0]);
    }

    @Override
    public int compare(T left, T right) {
        for (Comparator<? super T> comparator : comparators) {
            int result = comparator.compare(left, right);
            if (result != 0) {
                return result;
            }
        }
        return 0;
    }

    @Override
    public boolean equals(Object object) {
        if (object == this) {
            return true;
        }
        if (object instanceof CompoundOrdering<?> that) {
            return Arrays.equals(this.comparators, that.comparators);
        }
        return false;
    }

    @Override
    public int hashCode() {
        return Arrays.hashCode(comparators);
    }

    @Override
    public String toString() {
        return "Ordering.compound(" + Arrays.toString(comparators) + ")";
    }
}
