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

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

import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.StringTokenizer;

public class SSNVerificationResponseProcessrProcessCompletedHandler extends
		ExceptionWriterProcessCompletedHandler {

	private static String DATE_FORMAT = "yyyyMMddHHmmss";

	private String renameInputFileExtension;

	private String renameInputFileRoot;

	public String getRenameInputFileExtension() {
		return renameInputFileExtension;
	}

	public void setRenameInputFileExtension(String renameInputFileExtension) {
		this.renameInputFileExtension = renameInputFileExtension;
	}

	public String getRenameInputFileRoot() {
		return renameInputFileRoot;
	}

	public void setRenameInputFileRoot(String renameInputFileRoot) {
		this.renameInputFileRoot = renameInputFileRoot;
	}

	protected Object getExceptionFileNameSuffixData(
			DataProcessExecutionContext context) {
		Date executionStartDate = 
			context.getProcessStatistics().getProcessingStartDate();
		return executionStartDate;
	}

	// 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 (!renameFile(inputFile))
					throw new IllegalStateException(
							"Unable to rename input file: "
									+ inputFile.getName());
			}
		}
	}

	public void appendExceptionData(DataProcessExecutionContext context) {


		File inputFile = ((DataFileProcessExecutionContext) context)
		.getCurrentFile();
		String inputFileName = inputFile.getPath();
		
		getFileWriter().setFileLocation(inputFileName);


		
		// 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));
		}
	}

	protected boolean renameFile(File inputFile) {
		String inputFilePath = inputFile.getParent();
		StringBuffer inputFileNameRoot = new StringBuffer("");
		StringTokenizer st = new StringTokenizer(inputFile.getName(), ".");
		int tokenCount = st.countTokens();
		for (int i = 1; i < tokenCount; i++) {
			inputFileNameRoot.append(st.nextToken());
			if (i != (tokenCount - 1))
				inputFileNameRoot.append(".");
		}
		if (tokenCount == 1)
			inputFileNameRoot.append(inputFile.getName());

		String newFileName = null;
		if (renameInputFileRoot != null)
			newFileName = renameInputFileRoot + renameInputFileExtension;
		else
			newFileName = inputFileNameRoot.toString()
					+ renameInputFileExtension;
		File newFile = new File(inputFilePath + File.separator + newFileName);
		int i = 1;
		while (newFile.exists()) {
			if (logger.isWarnEnabled())
				logger
						.warn("Can not rename file to "
								+ newFile.getName()
								+ " since it exists already.  Trying one up number extension");

			newFile = new File(inputFilePath + File.separator + newFileName
					+ (i++));
		}
		boolean result = inputFile.renameTo(newFile);
		inputFile.setLastModified(new Date().getTime());
		return result;
	}

}
