package ru.yandex.wmconsole.data;


import java.util.Comparator;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import ru.yandex.common.util.db.OrderByClause;
import ru.yandex.wmconsole.data.info.UrlErrorsWithCodeInfo;

/**
 * User: baton
 * Date: 15.08.2007
 * Time: 16:46:03
 */
public class UrlErrorsWithCodeInfoComparator implements Comparator<UrlErrorsWithCodeInfo> {
    private static final Logger log = LoggerFactory.getLogger(UrlErrorsWithCodeInfoComparator.class);

    private enum UrlErrorInfoSortBy {
        SEVERITY("severity"),
        COUNT("count");

        private static final UrlErrorInfoSortBy DEFAULT_SORT_BY = SEVERITY;

        private final String arg;

        UrlErrorInfoSortBy(String arg) {
            this.arg = arg;
        }

        public static UrlErrorInfoSortBy getByArgument(String arg) {
            for (UrlErrorInfoSortBy sortBy : values()) {
                if (sortBy.arg.equals(arg)) {
                    return sortBy;
                }
            }

            return DEFAULT_SORT_BY;
        }
    }

    private final UrlErrorInfoSortBy urlErrorInfoSortBy;
    private final boolean asc;

    public UrlErrorsWithCodeInfoComparator(OrderByClause order) {
        this.urlErrorInfoSortBy = UrlErrorInfoSortBy.getByArgument(order.getColumnName());
        this.asc = order.isAscending();
    }

    @Override
    public int compare(UrlErrorsWithCodeInfo node1, UrlErrorsWithCodeInfo node2) {
        if (urlErrorInfoSortBy == UrlErrorInfoSortBy.SEVERITY) {
            int severityDiff = node1.getSeverity().getValue() - node2.getSeverity().getValue();
            if (severityDiff != 0) {
                return severityDiff * (asc ? 1 : -1);
            }
            return node1.getCode() - node2.getCode();
        } else if (urlErrorInfoSortBy == UrlErrorInfoSortBy.COUNT) {
            return (node1.getCount() - node2.getCount()) * (asc ? 1 : -1);
        } else {
            log.error("Unknown sorting type: " + urlErrorInfoSortBy);
            throw new AssertionError("Unknown sorting type");
        }
    }
}
