package lc.mecha.lang;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;

/**
 * This implementation provides a {@link Comparator} made out of one or more other comparators. This is useful for
 * doing multi-way sorts expressing functionality such as the SQL clause <code>SORT BY lastName, firstName</code>.
 */
public class MultiComparator<T> implements Comparator<T>, Serializable {
    private ArrayList<Comparator<T>> comparators = new ArrayList<>();

    public MultiComparator() {
        // Intentionally Blank
    }

    public MultiComparator(List<Comparator<T>> comparators) {
        this.comparators.addAll(comparators);
    }

    public void add(Comparator<T> c) {
        comparators.add(c);
    }

    public int compare(T arg0, T arg1) {
        for (Comparator<T> c : comparators) {
            int result = c.compare(arg0, arg1);
            if (result != 0) {
                return result;
            }
        }
        return 0;
    }
}