/********************************************************************
 * Copyright © 2006 VHA. All rights reserved
 ********************************************************************/
package gov.va.med.esr.common.persistent.history;

// Java imports
import gov.va.med.esr.common.model.registry.Registry;
import gov.va.med.esr.common.model.registry.RegistryTrait;
import gov.va.med.esr.common.model.registry.RegistryTraitDetail;
import gov.va.med.fw.model.AbstractVersionedEntity;
import gov.va.med.fw.persistent.DAOException;

import java.util.Set;

import org.apache.commons.lang.Validate;

/**
 * @author Muddaiah Ranga
 * @author DNS   CHENJ2
 * @version 1.0
 */
public class RegistryHistoryDAOImpl extends AbstractSingleAssocHistoryDAOImpl {

	/**
	 * 
	 */
	private static final long serialVersionUID = 3296615714430257180L;

	
	/**
	 * A default constructor
	 */
	public RegistryHistoryDAOImpl() {
		super();
	}

	/**
	 * Programatically remove delete records. Since we are dealing with a proxy,
	 * the reflection to access the private fields no longer works.
	 */
	protected void removeDeletedRecords(AbstractVersionedEntity entity)
			throws DAOException {

		// base implementation
		super.removeDeletedRecords(entity);
		
		// check the trait details and remove deleted records manually.
		// this is because the single ended object is returned as a proxy,
		// and the base history implementation attempts to access an object's
		// private fields.  This does not work with a proxy...
		RegistryTrait rt = ((Registry)entity).getRegistryTrait();

		if (rt != null) {
			Set traitDetails = rt.getRegistryTraitDetails();
			if (traitDetails != null)
				processDeleteSimpleSetNoReflection(traitDetails, rt);
		}
	}

	/**
	 * Invoked by processDeleteSimpleSetNoReflection. Child class to override.
	 * 
	 * @param parent
	 * @param child
	 */
	protected void removeChildOfProxiedObject(AbstractVersionedEntity proxiedObject,
			AbstractVersionedEntity child) 
	{
		Validate.isTrue(proxiedObject instanceof RegistryTrait);
		Validate.isTrue(child instanceof RegistryTraitDetail);

		((RegistryTrait) proxiedObject)
				.removeRegistryTraitDetail((RegistryTraitDetail) child);
	}

	/*
	 * 
	 * @see gov.va.med.esr.common.persistent.history.AbstractSingleAssocHistoryDAOImpl#getChild(gov.va.med.fw.model.AbstractVersionedEntity)
	 */
	protected AbstractVersionedEntity getSingleEndChild(AbstractVersionedEntity p) {
		
		Validate.isTrue(p instanceof Registry);
		return ((Registry)p).getRegistryTrait();
	}

	/*
	 * 
	 * @see gov.va.med.esr.common.persistent.history.AbstractSingleAssocHistoryDAOImpl#setSingleEndChild(gov.va.med.fw.model.AbstractVersionedEntity, gov.va.med.fw.model.AbstractVersionedEntity)
	 */
	protected void setSingleEndChild(AbstractVersionedEntity p, AbstractVersionedEntity c) {	 
	 
		Validate.isTrue(p instanceof Registry);
		Validate.isTrue(c instanceof RegistryTrait);

		((Registry) p).setRegistryTrait((RegistryTrait)c);
	}

}