package gov.va.med.ars.util;

import gov.va.med.ars.exceptions.ArsDataAccessException;
import gov.va.med.ars.spring.model.ClaimAttachments;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.Properties;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.FilenameUtils;
import org.apache.log4j.Logger;

public class FileUtils {
	
	static final Logger errorLogger = Logger.getLogger("errorLogger");
  
	public static Properties readPropertiesFile()
	{
		//Properties prop = new Properties();
		//InputStream input = null;
		Properties properties = new Properties();

		try {

			ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
			properties.load(classLoader.getResourceAsStream("ArsMaster.properties"));

		} catch (IOException ex) {
			errorLogger.error("Error reading ARS properties file attachment " + ex.getMessage());
		} 
		
		return properties;


	}  
	
	public void openAttachment(HttpServletRequest request,
			HttpServletResponse response, ClaimAttachments claimAttachment,
			String folderName) 
	{
		// get absolute path of the application
		ServletContext context = request.getSession().getServletContext();
		// construct the complete absolute path of the file
		String myFile = FilenameUtils.getBaseName(claimAttachment.getAttachmentName()) + "." + 
					    FilenameUtils.getExtension(claimAttachment.getAttachmentName());
		
		String fullPath = folderName + myFile;
		// get MIME type of the file

		String mimeType = context.getMimeType(fullPath);
		
		if (mimeType == null) 
		{ // set to binary type if MIME mapping not found 
			mimeType = "application/pdf";
		}

		System.out.println("MIME type: " + mimeType);

		//String headerKey = "Content-Disposition";
		//response.addHeader("Content-Disposition", "attachment;filename= " + myFile);
		
		response.setContentType("application/" + mimeType);
		
/*		if( mimeType.equalsIgnoreCase("pdf"))
		{
			response.setContentType("application/pdf");
		}
		else if ( mimeType.equalsIgnoreCase("txt"))
		{
			response.addHeader("Content-Disposition", "attachment;filename= " + myFile);
			response.setContentType("application/txt");
		}
		else if ( mimeType.equalsIgnoreCase("jpg"))
		{
			response.setContentType("application/jpg");
		}
		else if ( mimeType.equalsIgnoreCase("bmp"))
		{
			response.setContentType("application/bmp");
		}
		else if ( mimeType.equalsIgnoreCase("jpg"))
		{
			response.setContentType("application/jpg");
		}
		else if ( mimeType.equalsIgnoreCase("xml"))
		{
			response.setContentType("application/xml");
		}*/
		
		// get output stream of the response
		
		OutputStream outStream = null;
		
		try {

			response.reset();
			outStream = response.getOutputStream();
			
			byte[] buffer = claimAttachment.getAttachment();
			int bytesRead = buffer.length;
			// write bytes read from the input stream into the output stream
			/*
			 * while ((bytesRead = inputStream.read(buffer)) != -1) {
			 * outStream.write(buffer, 0, bytesRead); }
			 */
			System.out.println("bytesRead: " + bytesRead);
			outStream.write(claimAttachment.getAttachment(), 0, bytesRead);
			outStream.flush();
			//outStream.close();
		}
		catch (Exception e) {
			//e.printStackTrace();
			errorLogger.error("Error downloading attachment " + e.getMessage());
		}
/*		finally
		{
			try 
			{
				outStream.close();
			} catch (IOException io) {
				//io.printStackTrace();
				errorLogger.error("Error downloading attachment " + io.getMessage());
			}
		}*/


	}
	
	
	public static byte[] readAttachment(String fileName)
	{
		String myFile = FilenameUtils.getBaseName(fileName) + "." + 
				FilenameUtils.getExtension(fileName);

		String folderName = FileUtils.readPropertiesFile().getProperty("ars.server.save.location"); 
		String fullPath   = folderName + myFile;

		System.out.println("fullPath = " + fullPath);

		File file = new File(fullPath);

		FileInputStream fileInputStream = null;
		byte[] bFile = new byte[(int) file.length()];
		try
		{
			//convert file into array of bytes
			fileInputStream = new FileInputStream(file);
			fileInputStream.read(bFile);
			fileInputStream.close();
			/*	         for (int i = 0; i < bFile.length; i++)
	         {
	            System.out.print((char) bFile[i]);
	         }*/
		}
		catch (Exception e)
		{
			errorLogger.error("Error reading ARS file attachment " + e.getMessage());
			throw new ArsDataAccessException(e.getMessage() ,e);
		}

		return bFile;
		
	}
}
