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


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

import java.io.File;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.StringTokenizer;

import org.apache.commons.lang.StringUtils;

import gov.va.med.fw.batchprocess.DataFileProcessExecutionContext;
import gov.va.med.fw.batchprocess.DataProcessExecutionContext;
import gov.va.med.fw.batchprocess.ExceptionWriterProcessCompletedHandler;

/**
 * Initial javadoc for class HECLegacyDataSynchronizationConsumerProcessCompletedHandler.
 * TODO - Add content here
 * 
 * Created Mar 15, 2006 2:07:58 PM
 * @author DNS   BOHMEG
 */
public class HECLegacyDataSynchronizationConsumerProcessCompletedHandler extends
		ExceptionWriterProcessCompletedHandler {
	private static String DATE_FORMAT = "yyyyMMddHHmmss";
	
	protected Object getExceptionFileNameSuffixData(DataProcessExecutionContext context) {
		File inputFile = ((DataFileProcessExecutionContext) context).getCurrentFile();		
		String inputFileName = inputFile.getName();
		// remove the date from it and use it		
		// file naming convention: HECLegacytoESR_yyyyMMddHHmmss.dataSync
		String root = new StringTokenizer(inputFileName, ".").nextToken(); //HECLegacytoESR_yyyyMMddHHmmss
		StringTokenizer st = new StringTokenizer(root, "_");
		String date = null;
		while(st.hasMoreTokens()) 
			date = st.nextToken(); // get last token
		
		// make sure fully formed
		date = StringUtils.rightPad(date, DATE_FORMAT.length(), '0');
		
		SimpleDateFormat format = new SimpleDateFormat(DATE_FORMAT);
		
		try {
			return format.parse(date);
		} catch(ParseException e) {
			throw new IllegalArgumentException("File name [" + inputFileName + "] does not contain a date that is parsable to " +
					DATE_FORMAT);
		}
	}
	
	// override dataProcessingComplete to allow append instead of writing to the exception data file
	public void dataProcessingComplete(DataProcessExecutionContext context) {
		// append exception data instead of write
		appendExceptionData(context);
		
		// delete input file (if any)
		if(!context.isInterrupted()){
		    if(context instanceof DataFileProcessExecutionContext) {
			    File inputFile = ((DataFileProcessExecutionContext) context).getCurrentFile();
			    if (isDeleteInputFile() && !inputFile.delete())
				    throw new IllegalStateException("Unable to delete input file: "+ inputFile.getName());			
		    }
		}
	}
	
	public void appendExceptionData(DataProcessExecutionContext context) {
		
		// not calling getInterestedExceptionData since we are no longer filtering that list
		List exceptionData = context.getExceptionData();

		if (exceptionData != null && !exceptionData.isEmpty()) {

			// copy the list to another one for writing
			List currentExceptionData = new ArrayList(exceptionData);
		
			// lock the exception list within the context and remove data list
			synchronized(exceptionData) {
				exceptionData.clear();
			}
			
			getFileWriter().appendData(currentExceptionData, getExceptionFileNameSuffixData(context));		
		}
	}
}
