package com.k_int.aggr2.properties.hdo;

import javax.persistence.Column;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;


import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.Hibernate;
import org.hibernate.HibernateException;
import org.hibernate.Session;


@Table(name="CIIM_PROPERTY_NAMESPACE")
public class NamespaceHDO
{
    public static Log log = LogFactory.getLog(NamespaceHDO.class);
    private Long   id;
    private String uri;
    private String prefix;
    
    
    protected NamespaceHDO()
    {;}
    
    public NamespaceHDO(String uri,String prefix)
    {
        if(uri==null || prefix==null)
            throw new NullPointerException("Namespace and prefix must not be null");
        this.uri=uri;
        this.prefix=prefix;
    }
    
    protected void setId(Long id)
    {
    	this.id=id;
    }
    
    
    @Id
    @Column(name="ID")
    @GeneratedValue(strategy=GenerationType.AUTO)
    public Long getId() 
    {
      return id;
    }
    
    @Column(name="NS_PREFIX",length=32,unique=true)
    public String getPrefix()
    {
        return prefix;
    }
    
    @Column(name="NS_URI",length=255,unique=true)
    public String getNameSpace()
    {
        return uri;
    }
    
    public String toString()
    {
        return prefix+": "+uri;
    }
    
    public static NamespaceHDO lookupByUri(Session sess, String uri) throws PropertyException
	{
		if(uri==null)
			throw new NullPointerException("uri must not be null");
		try 
		{
		    org.hibernate.Query q = sess.createQuery("Select x from com.k_int.aggr2.properties.hdo.NamespaceHDO x where x.uri=?");
		    q.setParameter(0, uri, Hibernate.STRING);
		    return (NamespaceHDO) q.uniqueResult();
		}
		catch (HibernateException he) 
		{
			throw new PropertyException("Failed to look up namespace by uri: "+uri, he);
		}		  
	}
	
	public static NamespaceHDO lookupOrCreate(Session sess, String prefix, String uri) throws PropertyException
	{
		try 
		{
			NamespaceHDO retval = lookupByUri(sess,uri);
			if(retval==null)
			{
				if(uri==null || prefix==null)
					throw new NullPointerException("Uri and prefix must not be null");
				
				retval = new NamespaceHDO(prefix,uri);
				sess.save(retval);
			}
			return retval;
		}
		catch (HibernateException he) 
		{
				throw new PropertyException("Failed to create new namespace "+prefix+": "+uri);			    
		}
	}
}
