/*******************************************************************************
 * 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.importexport.ejb.session.beans;

import java.io.File;

import javax.ejb.Remote;
import javax.ejb.Stateful;
import javax.ejb.TransactionManagement;
import javax.ejb.TransactionManagementType;

import lu.tudor.santec.gecamed.core.ejb.entity.beans.GECAMedEntityBean;
import lu.tudor.santec.gecamed.core.ejb.session.beans.GECAMedSessionBean;
import lu.tudor.santec.gecamed.core.utils.FileUtils;
import lu.tudor.santec.gecamed.core.utils.ServerConfig;
import lu.tudor.santec.gecamed.importexport.ejb.session.interfaces.ImportExportInterface;
import lu.tudor.santec.gecamed.patient.ejb.entity.beans.IncidentEntry;
import lu.tudor.santec.gecamed.patient.ejb.entity.beans.Patient;

import org.apache.log4j.Level;
import org.apache.log4j.Logger;

/**
 * @author martin.heinemann@tudor.lu
 * 22.07.2008
 * 17:25:52
 *
 *
 * @version
 * <br>$Log: ImportExportBean.java,v $
 * <br>Revision 1.9  2013-12-27 18:09:26  donak
 * <br>Cleanup of imports
 * <br>
 * <br>Revision 1.8  2013-06-26 15:28:14  troth
 * <br>Code clean up syso.
 * <br>
 * <br>Revision 1.7  2012-03-15 08:16:24  ferring
 * <br>TimeTracker removed
 * <br>
 * <br>Revision 1.6  2008-09-25 09:43:07  heinemann
 * <br>fixed copyrights
 * <br>
 * <br>Revision 1.5  2008-07-28 16:10:28  heinemann
 * <br>*** empty log message ***
 * <br>
 * <br>Revision 1.4  2008-07-25 14:42:42  heinemann
 * <br>*** empty log message ***
 * <br>
 * <br>Revision 1.3  2008-07-23 15:37:53  heinemann
 * <br>*** empty log message ***
 * <br>
 * <br>Revision 1.2  2008-07-23 09:44:53  heinemann
 * <br>*** empty log message ***
 * <br>
 *   
 */
@Stateful
@TransactionManagement (TransactionManagementType.BEAN)
@Remote (ImportExportInterface.class)
public class ImportExportBean extends GECAMedSessionBean implements ImportExportInterface{

	/**
	 * static logger for this class
	 */
	private static Logger logger = Logger
		.getLogger(ImportExportBean.class.getName());
    
	public Patient savePatient(Patient patient) throws Exception {
    	return m_EntityManager.merge(patient);
    }
    
    public GECAMedEntityBean saveEntity(GECAMedEntityBean entity) throws Exception {
    	return m_EntityManager.merge(entity);
    }
    
    public void commitTransaction() throws Exception {
    	this.closeTransaction(true);
    }

    public void rollbackTransaction() throws Exception {
    	this.closeTransaction(false);
    }

    public void newTransaction() throws Exception {
    	this.openTransaction();
    }
    
    
    
    public IncidentEntry moveTempFile(IncidentEntry entry, Integer patientId) throws Exception {
        /* ================================================== */
//        TimeTracker.start("MOVE");
//        TimeTracker.lapTime("MOVE", "start moving " + entry.getFileName());
        File file = FileUtils.moveTempFileToPatientDir(entry.getFileName(), entry.getOriginalFilename(), patientId);
//        TimeTracker.lapTime("MOVE", "finish moving " + file.getAbsolutePath());
        /* ------------------------------------------------------- */
        // set the new file location to the entry
        /* ------------------------------------------------------- */
        entry.setFileName(file.getName());
        return entry;
        /* ------------------------------------------------------- */
        /* ================================================== */
    }
    
    
    /**
     * @param b the binary data of the file
     * @param entry containing the incident and the patient
     * @return the entry filled with the new file information
     * @throws Exception
     */
    public IncidentEntry saveGecamedFile(byte[] b, IncidentEntry entry) throws Exception {
    	/* ================================================== */
    	if (b != null && b.length > 0) {
			/* ------------------------------------------------------- */
			entry.setOriginalFilename(entry.getFileName());
			String genFilename = FileUtils.saveGECAMedPatientFile(b, 
											 entry.getFileName(), 
											 ServerConfig.getProperty(ServerConfig.PATIENT_FILES_DIR), 
											 entry.getIncident().getPatientId());
			entry.setFileName(genFilename);
			entry.setFileSize((long) b.length);
			
			return entry;
			/* ------------------------------------------------------- */
		}
    	return null;
    	/* ================================================== */
    }
    
    /**
     * @param filename
     * @param patientId
     * @throws Exception
     */
    public void deleteGecamedFile(String filename, Integer patientId) throws Exception {
    	/* ================================================== */
		// remove the attached file
		/* ------------------------------------------------------- */
		if (filename != null && !"".equals(filename)) {
			/* ------------------------------------------------------- */
			FileUtils.deleteGECAMedPatientFile(filename,
											   ServerConfig.getProperty(ServerConfig.PATIENT_FILES_DIR), 
											   patientId);
			/* ------------------------------------------------------- */
		}
    	/* ================================================== */
    }
    
    /**
     * Load the xsl-fo template from server
     * 
     * @param templateName
     * @return the file as byte array
     * @throws Exception
     */
    public byte[] getTemplateBinary(String templateName) throws Exception
    {
	    try {
	    	return FileUtils.getGECAMedFile(templateName, ServerConfig.getProperty(ServerConfig.TEMPLATE_DIR));		
	    } catch (Exception e) {
	    	logger.log(Level.WARN, "Error loading xsl-fo Template file: " + templateName + ".");
	    	throw e;
	    }
	}
}
