// Created May 24, 2005 3:20:46 PM

/********************************************************************
 * Copyright © 2005 VHA. All rights reserved
 ********************************************************************/

package gov.va.med.fw.persistent.hibernate;

import java.io.Serializable;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Types;

import org.apache.commons.lang.ObjectUtils;
import org.hibernate.HibernateException;
import org.hibernate.usertype.UserType;

import gov.va.med.fw.model.UserPrincipalImpl;
import gov.va.med.fw.security.SecurityContext;
import gov.va.med.fw.security.SecurityContextHelper;
import gov.va.med.fw.security.UserPrincipal;

/**
 * UserType for mapping Principal to a audit properties.
 * 
 * @author DNS   BOHMEG
 */
public class AuditUserType implements UserType {

	private static final int AUDIT_COLUMN_TYPE = Types.VARCHAR;

	public int[] sqlTypes() {
		return new int[] { AUDIT_COLUMN_TYPE };
	}

	public Class returnedClass() {
		return UserPrincipalImpl.class;
	}

	public boolean equals(Object x, Object y) throws HibernateException {
		return ObjectUtils.equals(x, y);
	}

	public int hashCode(Object x) throws HibernateException {
		return x.hashCode();
	}

	public Object nullSafeGet(ResultSet rs, String[] names, Object owner)
			throws HibernateException, SQLException {
		String name = rs.getString(names[0]); // get before null check
		if (rs.wasNull())
			return null;
		return new UserPrincipalImpl(name);
	}

	public void nullSafeSet(PreparedStatement st, Object value, int index)
			throws HibernateException, SQLException {
		if (value == null)
			st.setNull(index, AUDIT_COLUMN_TYPE);
		else {
			String name = SecurityContextHelper.getUserName((UserPrincipal) value);
			st.setString(index, SecurityContext.standardizeAuditId(name));
		}
	}

	public Object deepCopy(Object value) throws HibernateException {
		// TODO Auto-generated method stub
		return value;
	}

	public boolean isMutable() {
		// TODO Auto-generated method stub
		return false;
	}

	public Serializable disassemble(Object value) throws HibernateException {
		// TODO Auto-generated method stub
		return (Serializable) value;
	}

	public Object assemble(Serializable cached, Object owner) throws HibernateException {
		// TODO Auto-generated method stub
		return cached;
	}

	public Object replace(Object original, Object target, Object owner) throws HibernateException {
		// TODO Auto-generated method stub
		return original;
	}

}
