/*
 *  Copyright (c) 2001,2020 Alex Leigh, All Rights Reserved
 *
 *  THIS IS UNPUBLISHED PROPRIETARY SOURCE CODE OF ALEX LEIGH The copyright
 *  notice above does not evidence any actual or intended publication of such
 *  source code.
 *
 *  Use, disclosure, copying, distribution, or transmission of this code without
 *  express permission is prohibited.
 */

package leigh.eo.sort;

import leigh.eo.EO;
import leigh.mecha.log.MechaLogger;
import leigh.mecha.log.MechaLoggerFactory;
import leigh.mecha.sort.SortCardinality;
import leigh.mecha.util.StringUtil;

import java.util.Comparator;
import java.util.Locale;

/**
 * Implementation of a {@link Comparator} for {@link EO} which performs a {@link Locale}-specific standard
 * alphabetic sort.
 *
 * @author Alex Leigh
 */
public class EOStringComparator extends EOComparator {
    private static final MechaLogger logger = MechaLoggerFactory.getLogger(EOStringComparator.class);

    public EOStringComparator(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()));

        // Step 1, compare as if we are ascending.
        int result = getCollator().compare(v1, v2);

        switch (getCardinality()) {
            case ASCENDING:
                return result;
            case DESCENDING:
                if (result == 0) return 0;
                logger.debug("Descending case. [ret: {}] [orig: {}]", -result, result);
                return -result;
        }

        // Should never reach...
        throw new UnsupportedOperationException("Unknown cardinality.");
    }
}
