package cz.cuni.amis.pogamut.ut2004.communication.messages;

import java.util.HashMap;
import java.util.Map;

import cz.cuni.amis.pogamut.base.agent.worldview.objects.IWorldObjectId;
import cz.cuni.amis.utils.HashCode;

public class UnrealId implements IWorldObjectId {
	
	private static int lastId = 0;
	
	private static Map<String, UnrealId> ids = new HashMap<String, UnrealId>();
	
	public static UnrealId get(String unrealId) {
		synchronized(ids) {
			UnrealId id = ids.get(unrealId);
			if (id != null) return id;
			id = new UnrealId(unrealId, ++lastId);
			ids.put(unrealId, id);
			return id;
		}
	}
	
	private String unrealId;
	private int id;
	private final int hashCode;
	
	@Override
	public String getStringId() {
		return getUnrealId();
	}
	
	public String getUnrealId() {
		return unrealId;
	}

	public int getId() {
		return id;
	}

	private UnrealId(String unrealId, int id) {
		this.unrealId = unrealId;
		this.id = id;
		HashCode hc = new HashCode();
		hc.add(this.unrealId);
		hc.add(this.id);
		this.hashCode = hc.getHash();
	}
	
	public int hashCode() {
		return this.hashCode;
	}
	
	public boolean equals(Object obj) {
		if (obj instanceof UnrealId) {
			 if (this.id != 0) return this.id == ((UnrealId)obj).id;
			 return this.unrealId.equals(((UnrealId)obj).unrealId);
		} else {
			return false;
		}
	}
	
	public String toString() {
		return "UnrealId["+this.id+","+this.unrealId+"]";
	}

}
