package ru.yandex.wmconsole.data;

import java.util.Comparator;

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

import ru.yandex.common.util.db.OrderByClause;

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

    private enum ErrorTreeNodeChildrenSortBy {
        NAME("name"),
        COUNT("count");

        private static final ErrorTreeNodeChildrenSortBy DEFAULT_SORT_BY = NAME;

        private final String arg;

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

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

            return DEFAULT_SORT_BY;
        }
    }

    private final ErrorTreeNodeChildrenSortBy errorTreeNodeChildrenSortBy;
    private final boolean asc;

    public ErrorTreeNodeChildrenComparator(OrderByClause order) {
        this.errorTreeNodeChildrenSortBy = ErrorTreeNodeChildrenSortBy.getByArgument(order.getColumnName());
        this.asc = order.isAscending();
    }

    @Override
    public int compare(Node node1, Node node2) {
        if (errorTreeNodeChildrenSortBy == ErrorTreeNodeChildrenSortBy.NAME) {
            return node1.getInfo().getName().compareTo(node2.getInfo().getName()) * (asc ? 1 : -1);
        } else if (errorTreeNodeChildrenSortBy == ErrorTreeNodeChildrenSortBy.COUNT) {
            long diff = node1.getInfo().getUrlsInSubtree() - node2.getInfo().getUrlsInSubtree();
            return (int)Math.max(Math.min(diff, Integer.MAX_VALUE), Integer.MIN_VALUE) * (asc ? 1 : -1);
        } else {
            log.error("Unknown sorting type: " + errorTreeNodeChildrenSortBy);
            throw new AssertionError("Unknown sorting type");
        }
    }
}
