package gov.va.med.esr.service;

import gov.va.med.esr.model.ServiceLog;
import gov.va.med.fw.persistent.DAOException;
import gov.va.med.fw.persistent.DAOOperations;
import gov.va.med.fw.service.AbstractComponent;
import gov.va.med.fw.service.ServiceException;

public class ServiceLogServiceImpl extends AbstractComponent 
					implements ServiceLogService {
	
	private DAOOperations genericDAO;

	public DAOOperations getGenericDAO() {
		return genericDAO;
	}

	public void setGenericDAO(DAOOperations genericDAO) {
		this.genericDAO = genericDAO;
	}
	
	public ServiceLog saveLog(ServiceLog serviceLog) throws ServiceException{
		try {
			String originalRequest = serviceLog.getRequest();
			String truncatedRequest = truncateRequest(originalRequest);
			serviceLog.setRequest(truncatedRequest);
			ServiceLog newServiceLog = (ServiceLog) genericDAO.saveObject(serviceLog);
			newServiceLog.setRequest(originalRequest);
			return newServiceLog;
		}catch(DAOException de){
			throw new ServiceException(de);
		}
		
	}

	private String truncateRequest(String request) {
		int DB_REQUEST_COLUMN_MAXLIMIT = 4000;
		String truncatedRequest = null;
		byte [] originalRequestBytes = request.getBytes();
		byte [] truncatedRequestBytes = new byte[DB_REQUEST_COLUMN_MAXLIMIT];
		if (originalRequestBytes.length > DB_REQUEST_COLUMN_MAXLIMIT) {
			for (int i = 0; i < DB_REQUEST_COLUMN_MAXLIMIT; i++) {
				truncatedRequestBytes[i] = originalRequestBytes[i];
			}
			truncatedRequest = new String(truncatedRequestBytes);
		}
		
		return (truncatedRequest == null) ? request: truncatedRequest;
	}
	

}
