package com.fp.bpmlib.ejb;

import java.sql.Timestamp;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.annotation.PostConstruct;
import javax.ejb.Stateless;
import javax.ejb.TransactionAttribute;
import javax.ejb.TransactionAttributeType;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;

import com.fp.bpmlib.ejb.local.LogMailBeanLocal;
import com.fp.common.logger.APPLogger;
import com.fp.persistence.commondb.data.SessionData;
import com.fp.persistence.commondb.data.ThreadFacade;
import com.fp.persistence.pbpm.gene.TbpmLogMail;

/**
 * Clase utilitaria, utilizada para creacion de base de conocimento y RuntimeManager
 * 
 * @author Jvc
 * @version 2.1
 */
@Stateless(name="logMailBean")
public class LogMailBean implements LogMailBeanLocal {
//    @PersistenceUnit(unitName = "local1")
    private EntityManagerFactory emf;

    @PostConstruct
    private final void crearManager() {
        try {
            if (emf == null) {
            	Map<String, Object> configOverrides = new HashMap<String, Object>();
                configOverrides.put("hibernate.ejb.cfgfile", "hibernateFlipMapping.cfg.xml");
                emf = Persistence.createEntityManagerFactory("local1" , configOverrides);
            }
            SessionData sessionData = new SessionData();
            sessionData.setCompany(1);
            sessionData.setIsEjb(Boolean.FALSE);
            ThreadFacade.setSaveRequest(sessionData);
        } catch (Exception e) {
            APPLogger.getLogger().error(e);
        }
    }

    @TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
    public void logMail(Map<String, Object>  mapMail) throws Exception {
    	System.out.println("Ingresa al log del mail...................................");
    	EntityManager em=emf.createEntityManager();
    	TbpmLogMail logMail= new TbpmLogMail();
    	//logMail.setPk(getCodigo("CLOGMAIL"));
    	if(mapMail.get("subject")!=null){
    		logMail.setAsunto(mapMail.get("subject").toString());
    	}
    	if(mapMail.get("cont")!=null){
    		logMail.setContenido(mapMail.get("cont").toString());
    	}
    	if(mapMail.get("to")!=null){
    		logMail.setCorreo(mapMail.get("to").toString());
    	}
    	if(mapMail.get("error")!=null){
    		logMail.setDescripcionerror(mapMail.get("error").toString());
    	}
    	if(mapMail.get("estado")!=null){
    		logMail.setEstado(mapMail.get("estado").toString());
    	}
    	logMail.setFecharegistro(new Timestamp(new Date().getTime()));
    	if(em==null){
    		crearManager();
    		em=emf.createEntityManager();
    	}
    	
    	em.clear();
    	em.persist(logMail);
    	em.flush();
    	em.close();
    }
    

    /**
     * Entrega el entitymanagerfactory
     * 
     * @return
     */
    @Override
    public EntityManagerFactory getEmf() {
        return emf;
    }

}