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

import java.util.List;

import javax.ejb.Remote;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import lu.tudor.santec.gecamed.letter.ejb.entity.beans.Letter;
import lu.tudor.santec.gecamed.letter.ejb.session.interfaces.LetterInterface;

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

@Stateless
@Remote(LetterInterface.class)

/*
 * SessionBean that manages the LetterBeans
 */

public class LetterBean implements LetterInterface {
    
    	/**
	 * static logger for this class
	 */
	private static Logger logger = Logger.getLogger(LetterBean.class
		.getName());

	@PersistenceContext(unitName = "gecam")
	private EntityManager em;

	//adds a letter
	public boolean addLetter(Letter letter) {
		try {
			em.merge(letter);
			em.flush();
			return true;
		} catch (Exception e) {
		    	logger.log(Level.WARN, "error adding letter", e);
			return false;
		}
	}

	//returns a letter that corresponds to a specific IncidentEntry
	@SuppressWarnings("unchecked")
	public List<Letter> getLetterByIncidentEntry(int incedentEntryId) {
		List<Letter> result = em.createNamedQuery(
				Letter.FIND_BY_INCIDENTENTRY_ID).setParameter(
				"incidententry_id", incedentEntryId).getResultList();
		return result;
	}

	
	//return the types of the letters
	@SuppressWarnings("unchecked")
	public List<String> getTypes() {
		List<String> types = em.createNamedQuery(Letter.FIND_TYPES)
				.getResultList();
		return types;
	}

	//removes a letter that corresponds to a specific IncidentEntry
	public Boolean removeLetterbyIncidentId(Integer incidentEntryId) {
		try {
			Query q = em
					.createQuery("DELETE FROM Letter o WHERE o.incidentEntryID = "
							+ incidentEntryId);
			q.executeUpdate();
			return true;
		} catch (Exception e) {
		    	logger.log(Level.WARN, "error deleting letter", e);
			return false;
		}
	}

}
