package leigh.eo.sort;

import com.davekoelle.AlphanumComparator;
import leigh.eo.EO;
import leigh.mecha.sort.SortCardinality;
import leigh.mecha.util.StringUtil;

import java.util.Locale;

public class EOAlphaNumericComparator extends EOComparator {
    // Implementation must be threadsafe
    private final static AlphanumComparator comp = new AlphanumComparator();

    protected EOAlphaNumericComparator(String key, SortCardinality cardinality, Locale locale) {
        super(key, cardinality, locale);
    }

    @Override
    public int compare(EO o1, EO o2) {
        String v1 = StringUtil.safeString(o1.getValueString(getKey()));
        String v2 = StringUtil.safeString(o2.getValueString(getKey()));

        int result = comp.compare(v1, v2);

        switch (getCardinality()) {
            case ASCENDING:
                return result;
            case DESCENDING:
                if (result == 0) return 0;
                return -result;
        }

        return 0;
    }
}
