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

import java.io.PrintWriter;
import java.io.StringWriter;

import gov.va.med.esr.service.DemographicService;
import gov.va.med.fw.batchprocess.DataFileProcessExecutionContext;
import gov.va.med.fw.batchprocess.DataProcessExecutionContext;
import gov.va.med.fw.service.support.AbstractSpawnedThreadTask;

public class SSNVerificationResponseProcessSpawnedThreadTask extends
		AbstractSpawnedThreadTask {

	private DataFileProcessExecutionContext context;
	private SSASSNVerificationData dataRecord;
	private DemographicService demographicService;
	
	public DataFileProcessExecutionContext getContext() {
		return context;
	}
	public void setContext(DataFileProcessExecutionContext context) {
		this.context = context;
	}
	public SSASSNVerificationData getDataRecord() {
		return dataRecord;
	}
	public void setDataRecord(SSASSNVerificationData dataRecord) {
		this.dataRecord = dataRecord;
	}
	
	
	public DemographicService getDemographicService() {
		return demographicService;
	}
	
	public void setDemographicService(DemographicService demographicService) {
		this.demographicService = demographicService;
	}
	/*
	 * (non-Javadoc)
	 * 
	 * @see gov.va.med.fw.service.support.SpawnedThreadTask#execute()
	 */
	public void executeTask() throws Throwable {
		if (logger.isDebugEnabled()) {
			logger.debug("HECLegacyDataSynchronizationConsumerSpawnedThreadTask started");
		}
		try {
			
			if ( ! context.isInterrupted())
			{
				demographicService.updateSSNVerificationResponse(dataRecord);
				context.getProcessStatistics().incrementNumberOfSuccessfulRecords();
			}
		} catch (Exception e) {
			handleFailure(context, dataRecord, e);
		} finally {
			if (logger.isDebugEnabled()) {
				logger.debug("HECLegacyDataSynchronizationConsumerSpawnedThreadTask ended");
			}
			SSNVerificationResponseProcess.adjustTaskCount(
					context, -1);
			Object threadCreator = getThreadCreator(context);
			synchronized (threadCreator) {
				threadCreator.notifyAll();
			}
			if (logger.isDebugEnabled()) {
				logger.debug("SSNVerificationResponseProcessSpawnedThreadTask notified creator");
			}
			
			/*
			 * force release of context as thay will hold the ThreadPool(->Threads)
			 * this is necessary to GC ThreadPool threads at end
			 */
			context = null;
		}
	}
	
	
	private Object getThreadCreator(DataProcessExecutionContext context) {
		return context
				.getContextData()
				.get(
						SSNVerificationResponseProcess.CONTEXT_THREAD_CREATOR);
	}


	
	private void handleFailure(DataFileProcessExecutionContext context,
			SSASSNVerificationData identityData, Exception e) {
		String exceptionText = null;
		if (e == null) {
			exceptionText = "Error: Unable to process identity data: " + identityData;
		}
		else {
				exceptionText = "Error: Unable process for identity data: "
						+ identityData + " because of exception: " + e;		
		}
		if (logger.isErrorEnabled()) {
			logger.error(exceptionText);
		}
		context.getProcessStatistics().incrementNumberOfErrorRecords();
		context.getExceptionData().add(identityData);
		context.getExceptionData().add(exceptionText + "\n\n");
		
        if ( e != null )
        {
            StringWriter sw = new StringWriter();
            e.printStackTrace(new PrintWriter(sw));
            String trackTrace =  sw.toString();
            context.getExceptionData().add(trackTrace);
        }

		
 
	}

	

	
}
