/*******************************************************************************
 * This file is part of GECAMed.
 * 
 * GECAMed is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License (L-GPL) as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * GECAMed is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 * 
 * You should have received a copy of the GNU Lesser General Public License (L-GPL)
 * along with GECAMed.  If not, see <http://www.gnu.org/licenses/>.
 * 
 * GECAMed is Copyrighted by the Centre de Recherche Public Henri Tudor (http://www.tudor.lu)
 * (c) CRP Henri Tudor, Luxembourg, 2008
 *******************************************************************************/
package lu.tudor.santec.gecamed.patient.gui.fileimport;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.URLConnection;
import java.util.Map;
import java.util.Map.Entry;

import lu.tudor.santec.gecamed.core.gui.GECAMedModule;
import lu.tudor.santec.gecamed.core.gui.MainFrame;
import lu.tudor.santec.gecamed.core.utils.FileUtils;
import lu.tudor.santec.gecamed.core.utils.ManagerFactory;
import lu.tudor.santec.gecamed.patient.ejb.entity.beans.Incident;
import lu.tudor.santec.gecamed.patient.ejb.entity.beans.IncidentEntry;
import lu.tudor.santec.gecamed.patient.ejb.entity.beans.IncidentEntryType;
import lu.tudor.santec.gecamed.patient.ejb.session.beans.IncidentManagerBean;
import lu.tudor.santec.gecamed.patient.ejb.session.interfaces.IncidentManager;
import lu.tudor.santec.gecamed.patient.gui.PatientManagerModule;

import org.apache.log4j.Logger;

/**
 * @author martin.heinemann@tudor.lu
 * 10.03.2008
 * 15:24:53
 *
 *
 * @version
 * <br>$Log: FileImporter.java,v $
 * <br>Revision 1.15  2014-01-17 11:48:08  ferring
 * <br>Files are now attached correctly, with original file name and can be uploaded again
 * <br>
 * <br>Revision 1.14  2013-12-27 18:09:25  donak
 * <br>Cleanup of imports
 * <br>
 * <br>Revision 1.13  2013-07-15 06:18:36  ferring
 * <br>logging changed
 * <br>
 * <br>Revision 1.12  2013-02-28 13:00:21  ferring
 * <br>new files that shell be attached to a new incident are now attached to the same incident
 * <br>
 * <br>Revision 1.11  2013-02-22 08:46:50  kutscheid
 * <br>remove the tupel classes (please redeploy)
 * <br>
 * <br>Revision 1.10  2013-02-13 14:00:43  ferring
 * <br>stream closed
 * <br>
 * <br>Revision 1.9  2009-02-25 13:26:09  hermen
 * <br>added siteID to incidents and invoices
 * <br>
 * <br>Revision 1.8  2008-09-25 09:43:06  heinemann
 * <br>fixed copyrights
 * <br>
 * <br>Revision 1.7  2008-08-19 10:25:08  heinemann
 * <br>cleanup
 * <br>
 * <br>Revision 1.6  2008-07-18 13:44:32  heinemann
 * <br>*** empty log message ***
 * <br>
 * <br>Revision 1.5  2008-05-27 15:13:50  heinemann
 * <br>*** empty log message ***
 * <br>
 * <br>Revision 1.4  2008-04-09 09:39:43  heinemann
 * <br>*** empty log message ***
 * <br>
 * <br>Revision 1.3  2008-03-28 14:56:36  heinemann
 * <br>*** empty log message ***
 * <br>
 * <br>Revision 1.2  2008-03-27 12:35:47  weitz
 * <br>*** empty log message ***
 * <br>
 * <br>Revision 1.1  2008-03-11 17:17:11  heinemann
 * <br>*** empty log message ***
 * <br>
 *   
 */
public class FileImporter {
	
	
	
	public static final int STATE_OK 	  = 1;
	public static final int STATE_TOO_BIG = 2;
	public static final int STATE_ERROR   = 3;
	
	/** the logger Object for this class */
	private static Logger logger = Logger.getLogger(FileImporter.class.getName());
	
	
	private FileImporter() {
		/* ================================================== */

		/* ================================================== */
	}
	
	
	
	/**
	 * Import the given files into the database and link them to the incident
	 * 
	 * @param list
	 * @return
	 */
	public static boolean importFiles(Map<File, String> list, Incident incident) {
		/* ================================================== */
		boolean			state = false;
		IncidentManager	iManager;
		
		/* ------------------------------------------------------- */
		// create a new incident if the current is not present. ?-|
		/* ------------------------------------------------------- */
		if (incident == null && list != null && list.entrySet() != null && !list.entrySet().isEmpty()) {
			/* ------------------------------------------------------- */
			incident = new Incident(GECAMedModule.getCurrentPatient().getId(),
					MainFrame.getCurrentPhysician().getId());
			incident.setSiteId(MainFrame.getCurrentSiteId());
			iManager = (IncidentManager) ManagerFactory.getRemote(IncidentManagerBean.class);
			incident = iManager.saveIncident(incident);
			/* ------------------------------------------------------- */
		}
		
		for (Entry<File, String> entry : list.entrySet()) {
			/* ------------------------------------------------------- */
			state = importFile(entry.getKey(), entry.getValue(), incident);
			/* ------------------------------------------------------- */
		}
		
		return state;
		/* ================================================== */
	}
	
	
	/**
	 * @param file
	 */
	private static boolean importFile(File file, String description, Incident incident) {
		/* ================================================== */
//		BufferedInputStream bin = null;
		/* ------------------------------------------------------- */
		try {
			/* ------------------------------------------------------- */
			IncidentManager iManager = (IncidentManager) ManagerFactory.getRemote(IncidentManagerBean.class);
//			FileInputStream fin = new FileInputStream(file);
//			bin = new BufferedInputStream(fin);
//			byte[] b = new byte[(int) file.length()];
//			bin.read(b);
			byte[] fileBytes = FileUtils.readFile(file); 
			/* ------------------------------------------------------- */
			String mimeType = getMIMEType(file);
			/* ------------------------------------------------------- */
			// create a new incident entry type object
			/* ------------------------------------------------------- */
			IncidentEntryType type = new IncidentEntryType();
			type.setName(IncidentManager.FILE);
			type.setMimeType(mimeType);
			/* ------------------------------------------------------- */
			// create a new IncidentEntry object
			/* ------------------------------------------------------- */
			IncidentEntry ie = new IncidentEntry();
			/* ------------------------------------------------------- */
			// set the binary data
			/* ------------------------------------------------------- */
			ie.setBinaryContent(fileBytes);
			/* ------------------------------------------------------- */
			// set file name
			/* ------------------------------------------------------- */
			ie.setFileName(file.getName());
			ie.setOriginalFilename(file.getName());
			ie.setFileSize((long)fileBytes.length);
			/* ------------------------------------------------------- */
			ie.setTextContent(description);
			ie.setEntryType(type);
			ie.setIncident(incident);
			
			/* ------------------------------------------------------- */
			// save
			/* ------------------------------------------------------- */
			// letter/application/word
			/* ------------------------------------------------------- */
//			String extension = FilenameUtils.getExtension(ie.getFileName());
//			if (extension != null)
//				extension = extension.toLowerCase();
			
//			if ("doc".equals(extension) || "odt".equals(extension))
//				ie = iManager.saveEntry(ie, IncidentManager.LETTER);
//			else
			ie = iManager.saveEntry(ie, IncidentManager.FILE);
			
			return true;
			/* ------------------------------------------------------- */
		} catch (FileNotFoundException e) {
			logger.error("Error while storing attached file", e);
		}
		catch (IOException e) {
			logger.error("Error while storing attached file", e);
		}
//		finally
//		{
//			if (bin != null)
//			try
//			{
//				bin.close();
//			}
//			catch (IOException e)
//			{
//				logger.log(Level.ERROR, e.getMessage(), e);
//			}
//		}
		return false;
		/* ================================================== */ 
	}
	
	
	
	/**
	 * Easy but nor very robust solution to get the mime-type of a file
	 * @param file
	 * @return
	 */
	public static String getMIMEType( File file ) {
		/* ================================================== */
		 if ( !file.exists() )
		  throw new IllegalArgumentException( "File does not exit!" );
		 if ( file.isDirectory() )
		  return "directory";
		 try
		 {
			 URLConnection uCon = file.toURI().toURL().openConnection();
			 String mime = uCon.getContentType();
			 uCon.getInputStream().close();
			 /*this method is slow an alternative could be: new MimetypesFileTypeMap().getContentType(file)
			  * activation.jar is required
			  * http://java.sun.com/products/javabeans/glasgow/jaf.html
			  */
		  return mime;
		 }
		 catch ( IOException e )
		 {
		  throw new IllegalArgumentException( e.getMessage() );
		 }
	 /* ================================================== */
	}
	
	
	/**
	 * @param file
	 * @return
	 */
	public static int checkFile(File file) {
		/* ================================================== */
		if (file == null)
			return STATE_ERROR;
		/* ------------------------------------------------------- */
		if (file.isDirectory())
			return STATE_ERROR;
		/* ------------------------------------------------------- */
		// Read the file
		if (file.length() > PatientManagerModule.MAX_FILE_UPLOAD_SIZE) {
			System.out.println("TODO: file size exceeds maximum");
			return STATE_TOO_BIG;
		}
		return STATE_OK;
		/* ================================================== */
	}
	
	
}
