package aiouniya.analysis.mr;

import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;

//import org.apache.commons.lang.exception.ExceptionUtils;
import org.apache.hadoop.io.WritableComparable;
import org.apache.hadoop.io.WritableComparator;
import org.apache.hadoop.io.WritableUtils;

/**
 * 自定义MapOutputKey的类型，包含两个String
 *
 * @author wangqy
 * 
 */
public class StringPair implements WritableComparable<StringPair> {

	public StringPair() {
	}

	public StringPair(String first, String second) {
		this.first = first;
		this.second = second;
	}

	@Override
	public void readFields(DataInput in) throws IOException {
		set(WritableUtils.readString(in), WritableUtils.readString(in));
	}

	@Override
	public void write(DataOutput out) throws IOException {
		WritableUtils.writeString(out, getFirst());
		WritableUtils.writeString(out, getSecond());
	}

	@Override
	public int hashCode() {
		return (first.hashCode() * 179 + second.hashCode()) & Integer.MAX_VALUE;
	}

	@Override
	public boolean equals(Object right) {
		if (right instanceof StringPair) {
			StringPair r = (StringPair) right;
			return r.first.equals(first) && r.second.equals(second);
		} else {
			return false;
		}
	}

	public static class Comparator extends WritableComparator {
		public Comparator() {
			super(StringPair.class);
		}

		public int compare(byte[] b1, int s1, int l1, byte[] b2, int s2, int l2) {
			return compareBytes(b1, s1, l1, b2, s2, l2);
		}
	}

	static { // register this comparator
		WritableComparator.define(StringPair.class, new Comparator());
	}

	// 先比较第一个String（first），再比较第二个（second）
	@Override
	public int compareTo(StringPair o) {
		int cmp = first.compareTo(o.getFirst());
		if (cmp != 0) {
			return cmp;
		}
		return second.compareTo(o.getSecond());
	}

	@Override
	public String toString() {
		return first + "\t" + second;
	}

	public String getFirst() {
		return first;
	}

	public void setFirst(String first) {
		this.first = first;
	}

	public String getSecond() {
		return second;
	}

	public void setSecond(String second) {
		this.second = second;
	}

	public void set(String first, String second) {
		this.first = first;
		setSecond(second);
	}

	private String first;
	private String second;
}
