package ve.gob.cnti.receiver.jms;

import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Properties;
import java.util.logging.Logger;

import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.MapMessage;
import javax.jms.MessageConsumer;
import javax.jms.MessageProducer;
import javax.jms.ObjectMessage;
import javax.jms.Session;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;

import ve.gob.cnti.receiver.utils.PropertiesReader;

public class ConnectionJMS implements IConnectionJMS{
	
	
	PropertiesReader properties = new PropertiesReader();
    private final String DEFAULT_CONNECTION_FACTORY = properties.getProperty("DEFAULT_CONNECTION_FACTORY");
    public final String DEFAULT_EMAIL_DESTINATION = properties.getProperty("DEFAULT_EMAIL_DESTINATION");
    public final String DEFAULT_PROCESS_REGISTRY_DESTINATION = properties.getProperty("DEFAULT_PROCESS_REGISTRY_DESTINATION");
    public final String DEFAULT_USERS_ACTIVITIES_DESTINATION = properties.getProperty("DEFAULT_USERS_ACTIVITIES_DESTINATION");
    private final String DEFAULT_USERNAME = properties.getProperty("DEFAULT_USERNAME");
    private final String DEFAULT_PASSWORD = properties.getProperty("DEFAULT_PASSWORD");
    private final String INITIAL_CONTEXT_FACTORY = properties.getProperty("INITIAL_CONTEXT_FACTORY");
    private final String PROVIDER_URL = properties.getProperty("PROVIDER_URL");
    private ConnectionFactory connectionFactory = null;
    private Connection connection = null;
    private Session session = null;
    private MessageProducer producer = null;
    private MessageConsumer consumer = null;
    private Destination destination = null;
    private MapMessage mapMessage = null;
    private Context context = null;
    private ObjectMessage objMessage = null;
    private static final Logger log = Logger.getLogger(SenderJMS.class.getName());

	public void openConnection(final String COLA_DESTINO) {
		// TODO Auto-generated method stub
		try {
			
			 final Properties env = new Properties();
		     env.put(Context.INITIAL_CONTEXT_FACTORY, INITIAL_CONTEXT_FACTORY);
		     env.put(Context.PROVIDER_URL, System.getProperty(Context.PROVIDER_URL, PROVIDER_URL));
		     env.put(Context.SECURITY_PRINCIPAL, System.getProperty("username", DEFAULT_USERNAME));
		     env.put(Context.SECURITY_CREDENTIALS, System.getProperty("password", DEFAULT_PASSWORD));
		     try {
		    	 context = new InitialContext(env);
			  } catch (NamingException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
			  }
			
			String connectionFactoryString = System.getProperty("connection.factory", DEFAULT_CONNECTION_FACTORY);
	        log.info("Attempting to acquire connection factory \"" + connectionFactoryString + "\"");
			this.setConnectionFactory((ConnectionFactory) context.lookup(connectionFactoryString));
			log.info("Found connection factory \"" + connectionFactoryString + "\" in JNDI");
	
			String destinationString = System.getProperty("destination", COLA_DESTINO);
			log.info("Attempting to acquire destination \"" + destinationString + "\"");
			this.setDestination((Destination) context.lookup(destinationString));
			log.info("Found destination \"" + destinationString + "\" in JNDI");
	
			// 	Create the JMS connection, session, producer, and consumer
			this.setConnection(connectionFactory.createConnection(System.getProperty("username", DEFAULT_USERNAME), System.getProperty("password", DEFAULT_PASSWORD)));
			this.setSession(connection.createSession(false, Session.AUTO_ACKNOWLEDGE));
			this.setProducer(session.createProducer(destination));
			//  consumer = session.createConsumer(destination);						
			connection.start();	
			mapMessage = session.createMapMessage();
		} catch (Exception e){
			e.printStackTrace();
		}	
	}

	@Override
	public void closeConection() {
		// TODO Auto-generated method stub
		try{
			   if (this.getContext() != null) {		         
				   getContext().close();			
		       }
		       // closing the connection takes care of the session, producer, and consumer
		       if (this.getConnection() != null) {		     
		    	   this.getConnection().close();			
		       }
			} catch (NamingException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}  catch (JMSException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		
	}

	public ConnectionFactory getConnectionFactory() {
		return connectionFactory;
	}

	public void setConnectionFactory(ConnectionFactory connectionFactory) {
		this.connectionFactory = connectionFactory;
	}

	public Connection getConnection() {
		return connection;
	}

	public void setConnection(Connection connection) {
		this.connection = connection;
	}

	public Session getSession() {
		return session;
	}

	public void setSession(Session session) {
		this.session = session;
	}

	public MessageProducer getProducer() {
		return producer;
	}

	public void setProducer(MessageProducer producer) {
		this.producer = producer;
	}

	public MessageConsumer getConsumer() {
		return consumer;
	}

	public void setConsumer(MessageConsumer consumer) {
		this.consumer = consumer;
	}

	public Destination getDestination() {
		return destination;
	}

	public void setDestination(Destination destination) {
		this.destination = destination;
	}

	public MapMessage getMapMessage() {
		return mapMessage;
	}

	

	public void setMapMessage(MapMessage mapMessage) {
		this.mapMessage = mapMessage;
	}
	
   public void setMapMessage(Map<String,String> map) {
		Iterator<Entry<String, String>> interator=map.entrySet().iterator();
		while(interator.hasNext()) {
			    Entry<String, String> thisEntry = (Entry<String, String>) interator.next();
			    String key = (String)thisEntry.getKey();
			    String value = (String)thisEntry.getValue();			    
				try {
					this.mapMessage.setString(key, value);
				} catch (JMSException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
	      }
		
	}	

	
	public void setMapMessage(String key, String value) {
		try {
			this.mapMessage.setString(key,value);
		} catch (JMSException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public void setMapMessage(String key, byte[] value) {
		try {
			this.mapMessage.setBytes(key, value,0, value.length);
		} catch (JMSException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public void sendInfo(){
		try {
			producer.send(this.mapMessage);
		} catch (JMSException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	public Context getContext() {
		return context;
	}

	public void setContext(Context context) {
		this.context = context;
	}

	public ObjectMessage getObjMessage() {
		return objMessage;
	}

	public void setObjMessage(ObjectMessage objMessage) {
		this.objMessage = objMessage;
	}

	public String getDEFAULT_USERS_ACTIVITIES_DESTINATION() {
		return DEFAULT_USERS_ACTIVITIES_DESTINATION;
	}
	
	


}
