package ve.gob.cnti.receiver.ejb;

import java.io.UnsupportedEncodingException;
import java.util.logging.Logger;

import javax.ejb.ActivationConfigProperty;
import javax.ejb.MessageDriven;
import javax.jms.JMSException;
import javax.jms.MapMessage;
import javax.jms.Message;
import javax.jms.MessageListener;

import ve.gob.cnti.receiver.mail.IMail;
import ve.gob.cnti.receiver.mail.Mailer;
import ve.gob.cnti.receiver.utils.PropertiesReader;

/**
 * Message-Driven Bean implementation class for: ReceiverRecover
 */
@MessageDriven(
		activationConfig = { @ActivationConfigProperty(
				propertyName = "destination", propertyValue = "jms/queue/recover"), @ActivationConfigProperty(
				propertyName = "destinationType", propertyValue = "javax.jms.Queue")
		}, 
		mappedName = "jms/queue/recover")
public class ReceiverRecover implements MessageListener {	
	 private static final Logger log = Logger.getLogger(ReceiverRecover.class.getName());
    /**
     * Default constructor. 
     */
    public ReceiverRecover() {
        // TODO Auto-generated constructor stub
    }
	
	/**
     * @see MessageListener#onMessage(Message)
     */
    public void onMessage(Message message) {
        // TODO Auto-generated method stub
    	PropertiesReader properties = new PropertiesReader("templatesistema");		
    	String TEMPLATE_SUBJECT_GI_RECOVER = properties.getProperty("TEMPLATE_SUBJECT_GI_RECOVER");
    	String TEMPLATE_BODY_GI_RECOVER = properties.getProperty("TEMPLATE_BODY_GI_RECOVER");
    	PropertiesReader propertiesCongiguration = new PropertiesReader();		
    	MapMessage incoming = (MapMessage)message;
		IMail mail=new Mailer();
		String subject=TEMPLATE_SUBJECT_GI_RECOVER;
		log.info("asunto"+subject+TEMPLATE_SUBJECT_GI_RECOVER);				
		String texto=TEMPLATE_BODY_GI_RECOVER;
		log.info("templates"+TEMPLATE_SUBJECT_GI_RECOVER+TEMPLATE_BODY_GI_RECOVER+"url sistema"+propertiesCongiguration.getProperty("URL_SISTEMA"));	
		texto=texto.replace("${url}", propertiesCongiguration.getProperty("URL_SISTEMA").trim());
		mail=new Mailer();		
		try {
			log.info("email and body"+incoming.getString("body")+" "+incoming.getString("email"));
			texto+=incoming.getString("body");
			
			byte[] arr=null;
			try {
				arr = subject.getBytes("UTF-8");
			} catch (UnsupportedEncodingException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
			subject= new String(arr);
			
			try {
				arr = texto.getBytes("UTF-8");
			} catch (UnsupportedEncodingException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}			
	    	texto= new String(arr);
	    	
			mail.setToAddress(incoming.getString("email"));
			mail.setSubject(subject);
			mail.setBody(texto);
			mail.send();	
		} catch (JMSException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
				
			
		
        
    }

}
