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

/*
 * Created on Mar 8, 2006
 *
 */
package gov.va.med.esr.common.persistent.hibernate;


// Java classes
import java.util.Iterator;
import java.util.Set;

// Library classes

// Framework classes

// EDB Classes
import gov.va.med.esr.common.model.lookup.EmergencyResponse;
import gov.va.med.esr.common.model.person.EmergencyResponseIndicator;
import gov.va.med.esr.common.model.person.Person;
import gov.va.med.esr.common.util.DataSetupTestCase;

/**
 * @author Yi He
 * @version 1.0
 */
public class EmergencyResponseIndicatorTest extends DataSetupTestCase {
    private EmergencyResponseIndicator er = null;
    
    public EmergencyResponseIndicatorTest(String name) {
        super(name);
        super.setDefaultRollback(false);
    }
    
    public void setUpData() throws Exception {
	    er = new EmergencyResponseIndicator();
 	    EmergencyResponse em = (EmergencyResponse) getLookupService().getEmergencyResponseByCode("K");
	    er.setEmergencyResponse(em);
    }
    
    public void tearDownData() throws Exception {        
    	er = null;
    }
    
    public void testAddEmergencyResponseIndicatorAddress() throws Exception {
        try {
        	
        	// link address to person
        	Person p = getPerson();
        	p.addEmergencyResponseIndicator(er);
        	
	   	
        	// save address with person
        	personDao.saveObject(p);
	   	   	
        }
       	catch(Exception ex) {
       		ex.printStackTrace();
        	fail("Failed to add er address", ex);
        }        
    }
    


    public void testGetEmergencyResponseIndicator() throws Exception {
    	try {
    	    
    	   	// insert an er
	        Person p = getPerson();
	     	Set existingErs = p.getEmergencyResponseIndicators();
            if(existingErs.isEmpty()) {
	            p.removeAllEmergencyResponseIndicators();
	            p.addEmergencyResponseIndicator(er);
	       
    	      	// save er with person
	     	    personDao.saveObject(p);
            }
            
    	    // refresh data from database
	     	Person retrievedPerson = (Person) personDao.getByKey(p.getEntityKey());
	     	Set ers = retrievedPerson.getEmergencyResponseIndicators();
    	    Iterator iter = ers.iterator();
    	    System.out.println("got er from retrieved");
    	    while (iter.hasNext()) {
    	        EmergencyResponseIndicator em = (EmergencyResponseIndicator)iter.next();
    	        if (er.getEmergencyResponse().equals(em.getEmergencyResponse()))    		
    		    { 
    	        	logger.info("Got er right = " + em);
    		    	return;  
    		    }
    		    
            }
            fail("Could not find er ");
    	}
    	catch(Exception ex) {
    		fail("Failed to get er", ex);
    	}
    }
}

