/*
 * Created on Sep 24, 2004
 *
 * TODO To change the template for this generated file go to
 * Window - Preferences - Java - Code Style - Code Templates
 */
package gov.va.med.esr.common.persistent.comms.hibernate;

import java.util.Date;
import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.List;

import org.apache.commons.io.IOUtils;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import gov.va.med.fw.persistent.DAOException;
import gov.va.med.fw.persistent.hibernate.AbstractDAOImpl;
import gov.va.med.fw.service.ServiceException;

import gov.va.med.esr.common.model.comms.AacLetterRequest;
import gov.va.med.esr.common.persistent.comms.CommsTransLogDAO;
import gov.va.med.esr.common.persistent.comms.ExportFileDAO;

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

/**-----------------------------------------------------------------------
 *
 * <summary>Summary Description for ExportFileBroker</summary>
 * The ExportFileBroker is a file broker for ExportFileEntry class
 * to store an AAC export file to a specific directory. 
 * 
 * <owner>George Tsai</owner>
 * 
 * <remarks>
 * 
 * <history>
 * <u>version 1.0</u><br></br>module created<br></br>
 * </history>
 * 
 * </remarks>
 *
 *-----------------------------------------------------------------------
 */

	public class ExportFileDAOImpl  implements ExportFileDAO
	{
		//--------------------------------------------------------------------
		// Static variable(s)
		//--------------------------------------------------------------------
        private static final long serialVersionUID = -6919751063975875307L;
	    private String filePath = null;
	    private String cmsFilePath = null;	    
	    private CommsTransLogDAO commsTransLogDAO = null;
	    
        
		public ExportFileDAOImpl()
		{
			
		}

		//--------------------------------------------------------------------
		// Public method(s)
		//--------------------------------------------------------------------
		
		//format: WYYDDDNN.ltr  (Modified to use .tmp extension for CR8107)
		public String getAacFileName(String aacExtractId)
		{
                return aacExtractId + TEMP_FILE_EXTENSION;
		}
		
		public String getAacExtractId()
		{
            return getExtractId();
		}
		
		public String getOriginalAacFileName(String aacExtractId){
		        return aacExtractId +  FILE_EXTENSION;
		}
		
/**
 * Commented unused method 
 *         
//		private String assembleText(List requests, String aacExtractId)
//		{
//			StringBuffer str = new StringBuffer();
//
//			String entryText = null;
//			String fileName = getAacFileName(aacExtractId);
//			
//			AacLetterRequest req = null;
//			for (int i=0; i< requests.size(); i++)
//			{
//				req = (AacLetterRequest)requests.get(i);
//				entryText = postProcessAACText(req.getCommsLogEntry().getLogXML(), req.getCommsLogEntry().getEntityKey().getKeyValueAsString(), fileName, aacExtractId);
//				if( entryText != null && entryText.length()> 0)
//				{
//				    //set the final text
//				    req.setCommsPrintRequestXml(entryText);
//					str.append(entryText);
//				}
//			}
//
//			return str.toString();
//
//		}*/

		//Post Process AAC Text to add additional data element values
		//E04: extract date (file generation date)
		//E10: extract id (file name)
		//E11: barcode Id (on envelope)
		//
//		/**
//         * Commented unused method no need to maintain
//		private String postProcessAACText(String aacText, String logId, String fileName, String aacExtractId)
//		{
//			if (aacText == null || aacText.length() == 0)
//				return null;
//			StringBuffer newText = new StringBuffer(aacText);
//			
//	
//			int e04 = newText.indexOf("E04=");
//			if (e04 != -1) 
//			    newText.insert(e04+4, (new SimpleDateFormat("MMddyyy")).format(new Date())); //TODO: MMddyyyy
//			
//			int e10 = newText.indexOf("E10=");
//			if (e10 != -1 )
//			    newText.insert(e10+4, getAacFileName(aacExtractId));
//			
//			int e11 = newText.indexOf("E11="); //right pad to make length = 21
//			if (e11 != -1)
//			    newText.insert(e11+4, padRight(21, logId, ' '));
//
//			return newText.toString();
//
//		}*/
 
		/// <summary>
		/// Store Updates (insert or modify) the object's state in the database
		/// </summary>
		/// <param name="obj">
		/// </param>
		public void save(String text, String aacExtractId) throws ServiceException
		{
			java.io.FileWriter fw = null;
			try
			{
			    String fullQualifiedFileName = getAacFilePath() + getAacFileName(aacExtractId);
			    
			    java.io.File file = new java.io.File(fullQualifiedFileName);
	
			    fw = new java.io.FileWriter(file,file.exists());
			    

			    fw.write(text);
			    fw.flush();
			    
			} catch (java.io.IOException ioe)
			{
				throw new ServiceException("#### Error saving AAC Export Letter File", ioe);
			} finally {
				if (fw != null) {
					IOUtils.closeQuietly(fw);
				}
			}
		}
		
		
		
		@Override
		public void saveCms(String text, String extractId) throws ServiceException {
			java.io.FileWriter fw = null;
			try
			{
			    String fullQualifiedFileName = getCmsFilePath() + getCmsFileName(extractId);;
			    
			    java.io.File file = new java.io.File(fullQualifiedFileName);
	
			    fw = new java.io.FileWriter(file,file.exists());
			    

			    fw.write(text);
			    fw.flush();
			    
			} catch (java.io.IOException ioe)
			{
				throw new ServiceException("#### Error saving AAC Export Letter File", ioe);
			} finally {
				if (fw != null) {
					IOUtils.closeQuietly(fw);
				}
			}
		}

		//Changes .tmp file to .ltr file
        public void changeTmpFilesToLtr() throws IOException{
            java.io.File dir = new java.io.File(getAacFilePath());
            String target = "";
            FilenameFilter filter = new FilenameFilter(){
                public boolean accept(File dir, String name){
                    return name.endsWith(TEMP_FILE_EXTENSION);
                }
            };
            String[] files = dir.list(filter);
            //ccr 10082 Added more null check.
            if(files !=null){
            	for(int i=0; i<files.length; i++){
            		String extn = getFileExtension(files[i]);
            		if(extn.equalsIgnoreCase("tmp")){
            			target = files[i].replaceAll("."+extn, FILE_EXTENSION);
            			new File(getAacFilePath()+files[i]).renameTo(new File(getAacFilePath()+target));
            		}
                }
            }
        }
        public static String getFileExtension(String f) {
            String ext = "";
            int i = f.lastIndexOf('.');
            if (i > 0 &&  i < f.length() - 1) {
               ext = f.substring(i + 1).toLowerCase();
            }
            return ext;
         }		
        /**
         * @return Returns the filePath.
         */
        public String getAacFilePath() {
            if (filePath != null &&
                    !filePath.endsWith("/"))
                filePath += "/";
            
            return filePath;
        }
        
		public void changeCmsTmpFilesToLtr() throws IOException {
			String path = getCmsFilePath();
			java.io.File dir = new java.io.File(path);
			String target = "";
			FilenameFilter filter = new FilenameFilter(){
				public boolean accept(File dir, String name){
					return name.endsWith(TEMP_FILE_EXTENSION);
				}
			};
			String[] files = dir.list(filter);
			if(files !=null){
				for(int i=0; i<files.length; i++){
					String extn = getFileExtension(files[i]);
					if(extn.equalsIgnoreCase("tmp")){
						target = files[i].replaceAll("."+extn, FILE_EXTENSION);
						new File(path+files[i]).renameTo(new File(path+target));
					}
				}
			}
		}

		public String getCmsExtractId() {
			SimpleDateFormat sdf = new SimpleDateFormat("yyDDD");
					
			String fileNameBeforeVersion = FILE_PREFIX + sdf.format(new Date());

			return fileNameBeforeVersion + getFileVersion(fileNameBeforeVersion); 	
		}

		public String getCmsFileName(String cmsExtractId) {
			return cmsExtractId + TEMP_FILE_EXTENSION;
		}

		public String getCmsFilePath() {
            if (cmsFilePath != null &&
                    !cmsFilePath.endsWith("/"))
            	cmsFilePath += "/";
			
			return cmsFilePath;
		}

		public String getOriginalCmsFileName(String cmsExtractId) {
	        return cmsExtractId +  FILE_EXTENSION;
		}

		public void setCmsFilePath(String cmsFilePath) {
			this.cmsFilePath = cmsFilePath;
		}

		/**
         * @param filePath The filePath to set.
         */
        public void setAacFilePath(String filePath) {
            
            this.filePath = filePath;
        }
        
        public CommsTransLogDAO getCommsTransLogDAO() {
            return commsTransLogDAO;
        }

        public void setCommsTransLogDAO(CommsTransLogDAO commsTransLogDAO) {
            this.commsTransLogDAO = commsTransLogDAO;
        }

        
		//--------------------------------------------------------------------
		// Private method(s)
		//--------------------------------------------------------------------
        
		private String padRight(int length, String str, char c)
		{
			if (length == 0 || str == null)
				return null;
			
			int i = length - str.length();

			StringBuffer sbuf = new StringBuffer();
			
			while ( i > 0)
			{
				sbuf.insert(0, c);
				i--;
			}

			return sbuf + str;
		}
        
		private String getExtractId()
		{			
			//format: WYYDDDNN
			
			SimpleDateFormat sdf = new SimpleDateFormat("yyDDD");
					
			String fileNameBeforeVersion = FILE_PREFIX + sdf.format(new Date());

			return fileNameBeforeVersion + getFileVersion(fileNameBeforeVersion); 	
		}
		
        private String getFileVersion(String fileNameBeforeVersion)  {
            String versionStr = "01";
            String latestFileName = commsTransLogDAO.findFileNameByMaxId(fileNameBeforeVersion);

            if (latestFileName != null && latestFileName.startsWith(fileNameBeforeVersion)) {
                int beginIndex = fileNameBeforeVersion.length();
                int endIndex = latestFileName.length() - TEMP_FILE_EXTENSION.length();
                
                if (endIndex > beginIndex) {
                    String lastVersionStr = latestFileName.substring(beginIndex, endIndex);
                    int lastVersionNum = Integer.parseInt(lastVersionStr);
                    
                    lastVersionNum++;
                    if (lastVersionNum < 10) {
                        versionStr = "0" + lastVersionNum; //left pad with 0
                    }
                    else {
                        versionStr = String.valueOf(lastVersionNum);
                    }
                }
            }
            
            return versionStr;
        }
        

	}

