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 GraphUpdate implements Serializable {
	
	public enum GraphUpdateType { ADD, REMOVE }
	
	private String ev1, ev2;
	private GraphUpdateType op;
	private int hashcode;
	
	public GraphUpdate(String ev1, String ev2, GraphUpdateType op) {
		this.ev1 = ev1;
		this.ev2 = ev2;
		this.op = op;
		hashcode = Objects.hash(ev1, ev2, op);		
	}
	
	private void writeObject(java.io.ObjectOutputStream out) throws IOException {
		out.writeObject(ev1);
		out.writeObject(ev2);
		out.writeObject(op);
		out.writeObject(hashcode);
	}

	private void readObject(java.io.ObjectInputStream in) throws IOException, ClassNotFoundException {
		this.ev1 = (String) in.readObject();
		this.ev2 = (String) in.readObject();
		this.op = (GraphUpdateType) in.readObject();
		this.hashcode = (int) in.readObject();
	}
	
	public String getEvent1() { return ev1; }
	public String getEvent2() { return ev2; }
	public GraphUpdateType getOp() { return op; }
	
	public String toString() {
		return op == GraphUpdateType.ADD ? "ADD (" + ev1 + ", " + ev2 + ")" : "REM (" + ev1 + ", " + ev2 + ")";  
	}
	
	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());
	}

	// The following two functions are necessary as we may 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 GraphUpdate)
			return this.ev1.equals( ((GraphUpdate)other).ev1) && this.ev2.equals( ((GraphUpdate)other).ev2) && this.op == ((GraphUpdate)other).op;
		else 
			return false;
	}
	
}
