package kinesisFHM.commonTypes;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.Objects;

import org.apache.commons.codec.binary.Base64;

public class EventPair implements Serializable {
	private String event1, event2;
	private int hashcode;
	
	public EventPair(String ev1, String ev2) {
		this.event1 = ev1;
		this.event2 = ev2;
		hashcode = Objects.hash(event1, event2);
	}
	
	public EventPair(EventPair ep) {
		this.event1 = ep.event1;
		this.event2 = ep.event2;
		hashcode = Objects.hash(event1, event2);
	}

	public void set(String ev1, String ev2) {
		event1 = ev1;
		event2 = ev2;
		hashcode = Objects.hash(event1, event2);
	}
	
	public String getEvent1() {
		return event1;
	}

	public String getEvent2() {
		return event2;
	}

	public int compareTo(EventPair other) {
		int c = event1.compareTo(other.event1);
		if (c != 0) return c;
		return event2.compareTo(other.event2);
	}

	private void writeObject(java.io.ObjectOutputStream out) throws IOException {
		out.writeObject(event1);
		out.writeObject(event2);
		out.writeObject(hashcode);
	}

	private void readObject(java.io.ObjectInputStream in) throws IOException, ClassNotFoundException {
		this.event1 = (String) in.readObject();
		this.event2 = (String) in.readObject();
		this.hashcode = (int) in.readObject();
	}

	public String toString() {
		return "<" + event1 + ", " + event2 + ">";
	}

	// The following two functions are necessary as we use these as key in a HashMap
	public int hashCode() {
		return hashcode;
    }
	public boolean equals(Object other) {
		if (other == null) return false;
		if (other instanceof EventPair)
			return this.event1.equals( ((EventPair)other).event1) && this.event2.equals( ((EventPair)other).event2);
		else 
			return false;
	}
	
	public byte[] getBase64() {
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		try {
			new ObjectOutputStream( baos ).writeObject( this );
		} catch (IOException e) {
			return new byte[]{0};
		}
		return Base64.encodeBase64(baos.toByteArray());
	}
}
