package gov.va.med.cds.util;

import java.util.Arrays;
import java.util.HashMap;

import org.dom4j.DocumentFactory;
import org.dom4j.Element;

public class QueryCacheKey
{
	private String queryIdentifier;
	private HashMap<String, Object> paramsMap = new HashMap<String, Object>();

	public QueryCacheKey(String queryIdentifier)
	{
		this(queryIdentifier,null,null);
	}
	
	public QueryCacheKey(String queryIdentifier, String paramName, Object paramValue) 
	{
		if ( queryIdentifier==null ) throw new IllegalArgumentException("queryIdentifier cannot be null");
		this.queryIdentifier = queryIdentifier;
		if ( paramName!=null && !paramName.trim().equals(""))paramsMap.put(paramName, paramValue);	
	}
	
	public QueryCacheKey(String queryIdentifier,HashMap<String, Object> paramsMap) 
	{
		if ( queryIdentifier==null ) throw new IllegalArgumentException("queryIdentifier cannot be null");
		this.queryIdentifier = queryIdentifier;
		if ( paramsMap!=null ) this.paramsMap=paramsMap;
	}
	
	public String toString()
	{
		return toElement().asXML();	
	}
	
	public Element toElement()
	{
		DocumentFactory df = new DocumentFactory();
		Element e = df.createElement(getClass().getSimpleName());
		e.add(df.createAttribute(e, "queryIdentifier", queryIdentifier));
		int index = 0; 
		for ( String key: paramsMap.keySet() )
		{
			e.add(df.createAttribute(e, "queryParameterName"+index, key));
			e.add(df.createAttribute(e, "queryParameterValue"+index,paramsMap.get(key).toString()));
			index++;
		}
		return e;
	}
	
	
	@Override
	public boolean equals(Object object)
	{
		if ( this == object) return true;
		try
		{
			QueryCacheKey other = (QueryCacheKey)object;
			if ( !queryIdentifier.equals(other.queryIdentifier)) return false;
			if ( !paramsMap.equals(other.paramsMap)) return false;
			return true;			
		}
		catch ( Exception e)
		{
			return false;
		}
	}
	
	@Override
	public int hashCode() 
	{ 
		return Arrays.hashCode(new Object[] { queryIdentifier, paramsMap });		
    }

	
}
