package gov.va.med.esr.common.batchprocess;



import java.math.BigDecimal;
import java.util.Date;
import java.util.Hashtable;
import java.util.Enumeration;
import java.util.List;

import org.apache.commons.lang.StringUtils;

import gov.va.med.esr.common.model.comms.AacLetterRequest;
import gov.va.med.esr.common.model.comms.CommsLogEntry;
import gov.va.med.esr.common.model.comms.CommsTemplate;
import gov.va.med.esr.common.model.comms.ExportSnapshot;
import gov.va.med.esr.common.model.lookup.AddressType;
import gov.va.med.esr.common.model.lookup.ComLetterTemplateType;
import gov.va.med.esr.common.model.lookup.ComLetterType;
import gov.va.med.esr.common.model.lookup.ComMailingTriggerType;
import gov.va.med.esr.common.model.lookup.SSNType;
import gov.va.med.esr.common.model.person.Person;
import gov.va.med.esr.common.model.person.SSN;
import gov.va.med.esr.common.model.person.id.PersonIdEntityKeyImpl;
import gov.va.med.esr.common.model.report.ReportSetup;
import gov.va.med.esr.common.persistent.comms.AacLetterRequestDAO;
import gov.va.med.esr.common.persistent.comms.CommsLogEntryDAO;
import gov.va.med.esr.common.persistent.comms.CommsTemplateDAO;
import gov.va.med.esr.common.persistent.comms.ExportSnapshotDAO;
import gov.va.med.esr.common.util.LetterFormatHelper;
import gov.va.med.esr.common.util.RuleAbstractTestCase;
import gov.va.med.esr.service.PersonService;
import gov.va.med.esr.service.trigger.LetterTrigger;
import gov.va.med.esr.service.trigger.LetterTriggerIdentity;
import gov.va.med.fw.batchprocess.DataProcessExecutionContext;
import gov.va.med.fw.model.EntityKey;
import gov.va.med.fw.model.EntityKeyFactory;
import gov.va.med.fw.scheduling.ScheduledProcess;



/**
 * @author DNS   TSAIG
 *
 * TODO To change the template for this generated type comment go to
 * Window - Preferences - Java - Code Style - Code Templates
 */



public class TestAacExportCommand extends RuleAbstractTestCase {

   private ExportSnapshotDAO snapShotDAO = null;	
   private AacLetterRequestDAO requestDAO = null;
	
    public TestAacExportCommand(String testName) {
        super(testName);
    }

    public void setUpData() throws Exception {
    }

    public void tearDownData() throws Exception {

    }

    public void testCommsLog() throws Exception {
    	CommsLogEntryDAO dao =   (CommsLogEntryDAO)applicationContext.getBean("commsLogEntryDAO");
    	CommsLogEntry log = new CommsLogEntry();
    	log.setPersonId(new BigDecimal("375124624"));
    	log.setLetterType(this.getLookupService().getComLetterTypeByCode(ComLetterType.CODE_ENROLLMENT.getCode()));
    	dao.insert(log);
    	// do not persist... this gets rolled back... only for testing that mapping is OK
    }
    public void testComLetterTemplateType() throws Exception {
    	ComLetterTemplateType type =  this.getLookupService().getComLetterTemplateTypeByCode(ComLetterTemplateType.FORM_NUMBER_400.getCode());
    	junit.framework.Assert.assertEquals("742-400", type.getCode());
    	type =  this.getLookupService().getComLetterTemplateTypeByCode(ComLetterTemplateType.FORM_NUMBER_450.getCode());
    	junit.framework.Assert.assertEquals("742-450", type.getCode());
    	type =  this.getLookupService().getComLetterTemplateTypeByCode(ComLetterTemplateType.FORM_NUMBER_451.getCode());
    	junit.framework.Assert.assertEquals("742-451", type.getCode());    
    	type =  this.getLookupService().getComLetterTemplateTypeByCode(ComLetterTemplateType.FORM_NUMBER_452.getCode());
    	junit.framework.Assert.assertEquals("742-452", type.getCode());    
    	type =  this.getLookupService().getComLetterTemplateTypeByCode(ComLetterTemplateType.FORM_NUMBER_453.getCode());
    	junit.framework.Assert.assertEquals("742-453", type.getCode());    
    	type =  this.getLookupService().getComLetterTemplateTypeByCode(ComLetterTemplateType.FORM_NUMBER_454.getCode());
    	junit.framework.Assert.assertEquals("742-454", type.getCode());    
    	type =  this.getLookupService().getComLetterTemplateTypeByCode(ComLetterTemplateType.FORM_NUMBER_455.getCode());
    	junit.framework.Assert.assertEquals("742-455", type.getCode());
    	type =  this.getLookupService().getComLetterTemplateTypeByCode(ComLetterTemplateType.FORM_NUMBER_683A.getCode());
    	junit.framework.Assert.assertEquals("683A", type.getCode());        	
    }    
    

    public void testAacExportCommand_executeSingle() throws Exception {

    	Person person = this.buildSimplePerson();
    	person.addAddress(this.createAddress(
    			this.getLookupService().getAddressTypeByCode(AddressType.CODE_PERMANENT_ADDRESS.getCode())));          
    	this.attachVerifiedEnrollment(person);
    	SSN ssn = this.createSSN(); 
    	ssn.setType(this.getLookupService().getSSNTypeByCode(SSNType.CODE_ACTIVE.getName()));
    	person.addSsn(ssn);		
    	Person onFile = this.savePerson(person);    	
    	 
    	CommsLogEntry log = new CommsLogEntry();
    	log.setPersonId(new BigDecimal("375124624"));
    	log.setAddress(onFile.getPermanentAddress());

    	CommsTemplate templ = new CommsTemplate();
    	templ.setLetterType(this.getLookupService().getComLetterTypeByCode(ComLetterType.CODE_IVM.getCode()));
    	templ.setCommsTemplateName("Copay Exempt(Priority Group 5)");

    	log.setTemplate(templ);
    	templ.setCommsTemplateFormNumber(ComLetterTemplateType.FORM_NUMBER_400.getCode());
    	AacLetterRequest request = new AacLetterRequest();
    	request.setCommsLogEntry(log);
    	request.setCommsTemplateFormNumber(templ.getCommsTemplateFormNumber());

    	AacExportCommand cmd = (AacExportCommand) applicationContext.getBean("aacExportCommand");
    	String[] args = null;
    	InitiateAACLetterExportProcess process = new InitiateAACLetterExportProcess();
    	DataProcessExecutionContext context = new DataProcessExecutionContext() ;
    	CommsExportStatistics stats = new CommsExportStatistics();
    	stats.setStartTime(new Date());           

    	cmd.executeSingle(context, process, request, stats, "345345");
    }
    
    public void testCommsExportStatistics() throws Exception {
     	CommsExportStatistics stats = new CommsExportStatistics();
    	stats.setStartTime(new Date());               	
    	stats.setNumberSent(0);    	
    	AacLetterRequest request = new AacLetterRequest();
    	request.setCommsTemplateFormNumber(ComLetterTemplateType.FORM_NUMBER_400.getCode());
    	stats.addToCountPerFormTable(request);
    	request.setCommsTemplateFormNumber(ComLetterTemplateType.FORM_NUMBER_600C.getCode());
    	stats.addToCountPerFormTable(request);    	
        Hashtable dataTab = stats.getCountPerFormTable();
        Enumeration e = dataTab.keys();
        while (e.hasMoreElements()) {
        	System.out.println(e.nextElement());
        }
        String s = "742-600C to be send to AAC = 1\n742-400 to be send to CMS = 1\n";
        String text = stats.getCountPerFormTableText();
        System.out.println(text);
    	assertEquals(s, text);
    }
    
    public void testAACandCMS_LetterExport() throws Exception {
     	CommsExportStatistics stats = new CommsExportStatistics();
    	stats.setStartTime(new Date());               	
    	stats.setNumberSent(0);
    	//String personId = "375124624";
    	//378177224
    	//String personId = "6417462";
    	String personId = "8859561";
    	//8859561
		PersonIdEntityKeyImpl personKey = new PersonIdEntityKeyImpl(new BigDecimal(personId));
		Person person = this.getPersonService().getPerson(personKey);    	
		CommsLogEntryDAO dao =   (CommsLogEntryDAO)applicationContext.getBean("commsLogEntryDAO");
		EntityKey key = EntityKeyFactory.createEntityKey(new BigDecimal(378178285),CommsLogEntry.class);
		CommsLogEntry entryLog = (CommsLogEntry)dao.getByKey(key);

    	this.doexecuteSingle(personId, entryLog.getTemplate(), entryLog, stats);
    	System.out.println("stats=\n"+stats.getCountPerFormTableText()); 	
    }

    private void doexecuteSingle(String personId, CommsTemplate templ, 
    		CommsLogEntry log, CommsExportStatistics stats ) throws Exception {

    	AacExportCommand cmd = (AacExportCommand) applicationContext.getBean("aacExportCommand");
    	InitiateAACLetterExportProcess process = new InitiateAACLetterExportProcess();
    	DataProcessExecutionContext context = new DataProcessExecutionContext() ;
    	AacLetterRequestDAO dao =   (AacLetterRequestDAO)applicationContext.getBean("aacLetterRequestDAO");
    	EntityKey key = EntityKeyFactory.createEntityKey(new BigDecimal(378177397),AacLetterRequest.class);
		AacLetterRequest request = (AacLetterRequest)dao.getByKey(key);
    	cmd.executeSingle(context, process, request, stats, "345345");
    }    

	private String createUniqueCode(String personId,
			LetterTriggerIdentity letterType) {
		StringBuffer buf = new StringBuffer();
		buf.append(LetterFormatHelper.padLeft(personId, 21, '0')).append(
				AacLetterRequest.DUPE_CHECK_DELIMITER);
		buf.append(letterType.getDataType().getCode()).append(
				AacLetterRequest.DUPE_CHECK_DELIMITER);
		buf.append(letterType.getCategoryType().getName());
		return buf.toString();
	}    
    
    public void testSnapshot() throws Exception {
        ExportSnapshot currSnapShot = snapShotDAO.getCurrentSnapshot();
        System.out.println("num="+currSnapShot.getPrintRequestId().longValue());
    }
    public void testRequestBatch() throws Exception{
    	this.getLoginManager().loginAnonymous();
    	AacLetterRequestDAO dao = (AacLetterRequestDAO)applicationContext.getBean("aacLetterRequestDAO");
    	List requests = dao.findAacLetterRequestBetweenRequestIdsByBatch(new BigDecimal(372159791), new BigDecimal(377266370),1000 );
    	System.out.println("number="+requests.size());

    }
    public void testInitiateAACLetterExport() throws Exception{
    	//login anonymous
    	this.getLoginManager().loginAnonymous();
    	ScheduledProcess process = (ScheduledProcess)applicationContext.getBean("common.batchprocess.initiateAACLetterExport");
    	process.invoke(null);
    }
    public void testInitiateSingleAACLetterExport() throws Exception{
    	this.getLoginManager().loginAnonymous();
    	ScheduledProcess process = (ScheduledProcess)applicationContext.getBean("common.batchprocess.initiateAACLetterExport");
    	process.invoke(null);
    }    
    public void testHandbookBatchProcess() throws Exception{

        //login anonymous
        this.getLoginManager().loginAnonymous();

        try {
            ScheduledProcess process = (ScheduledProcess)applicationContext.getBean("common.batchprocess.handbookBatchProcess");
            process.invoke(null);
                    }
        catch( Exception e ) {
            e.printStackTrace();
            fail( "Failed to insert a log entry due to exception", e );
        }
    }
    
    public void testHandbookBatchProcessDeprecatedPerson() throws Exception{

        //login anonymous
        this.getLoginManager().loginAnonymous();

        ComLetterTemplateType formNumber = (ComLetterTemplateType)
        this.getLookupService().getByCode(ComLetterTemplateType.class, "742-400H");
        String personId= "373960659";
		List conditions = getHandBookService().requestHandBook(personId, new LetterTriggerIdentity(formNumber, LetterTrigger.CategoryType.VETERAN_LETTER));
		this.setComplete();
    
/*        try {
            ScheduledProcess process = (ScheduledProcess)applicationContext.getBean("common.batchprocess.handbookBatchProcess");
            process.invoke(null);
                    }
        catch( Exception e ) {
            e.printStackTrace();
            fail( "Failed to insert a log entry due to exception", e );
        }*/
    }

	public ExportSnapshotDAO getSnapShotDAO() {
		return snapShotDAO;
	}

	public void setSnapShotDAO(ExportSnapshotDAO snapShotDAO) {
		this.snapShotDAO = snapShotDAO;
	}

    
}
