package com.hammurapi.extract;

import java.util.Comparator;

import com.hammurapi.common.Util;

/**
 * Comparator which uses extraction.
 * @author Pavel Vlasov
 *
 * @param <V>
 */
public class ExtractorComparator<T,V extends Comparable<V>, C> implements Comparator<T> {
	
	private Extractor<T, V, C> extractor;
	private C context;

	public ExtractorComparator(Extractor<T, V, C> extractor, C context) {
		this.extractor = extractor;
		this.context = context;
	}

	@Override
	public int compare(T o1, T o2) {
		return extractor.extract(context, null, Util.wrap(o1)).compareTo(extractor.extract(context, null, Util.wrap(o2)));
	}

	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + ((context == null) ? 0 : context.hashCode());
		result = prime * result	+ ((extractor == null) ? 0 : extractor.hashCode());
		return result;
	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		ExtractorComparator other = (ExtractorComparator) obj;
		if (context == null) {
			if (other.context != null)
				return false;
		} else if (!context.equals(other.context))
			return false;
		if (extractor == null) {
			if (other.extractor != null)
				return false;
		} else if (!extractor.equals(other.extractor))
			return false;
		return true;
	}		

}
