package com.eactive.eai.common.routing;

import javax.jms.Connection;
import javax.jms.Destination;
import javax.jms.ExceptionListener;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageConsumer;
import javax.jms.ObjectMessage;
import javax.jms.Session;
import com.eactive.eai.batch.scheduler.ScheduleHandlerProcess;
import com.eactive.eai.batch.scheduler.ScheduleRecvProcess;
import com.eactive.eai.common.util.Logger;


public class TimerEventListener implements Runnable, ExceptionListener {

	static final String PROC_JOB = "요구송수신작업수행";
	static final String REG_JOB = "요구수신작업등록";

	private static Logger logger = Logger.getLogger(Logger.LOGGER_DEFAULT);

	Connection connection = null;
	Session session = null;
	MessageConsumer consumer = null;
	String name = null;
	String queue = null;
	boolean run = true;

	public TimerEventListener(String name, Connection con, String queue) {
		this.connection = con;
		try {
			this.name = name;
			this.queue = queue;
			connection.start();
			connection.setExceptionListener(this);

			// Create a Session
			session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);

			// Create the destination (Topic or Queue)
			Destination destination = session.createQueue(queue);
			consumer = session.createConsumer(destination);
		} catch (JMSException e) {
			logger.error(e.getMessage(), e);
		}
	}

	@Override
	public void run() {
		String messageStr = null;
		while (run) {
			try {
				if ( consumer == null ){
					run = false;
					continue;
				}
				Message message = consumer.receive(2000);

				ObjectMessage omsg = null;

				if (message == null) {
					// logger.warn(name + " -> EMPTY MESSAGE...");
					continue;
				}

				if (message instanceof ObjectMessage) {
					omsg = (ObjectMessage) message;
				} else {
					throw new RuntimeException(name + " Invlid JMS Message Type. - " + message);
				}

				try {
					messageStr = (String) omsg.getObject();
				} catch (Exception e) {
					throw new RuntimeException(name + " Invlid value object in ObjectMessage. - " + e.getMessage());
				}

				try {
					if (messageStr.equals(PROC_JOB)) {
						ScheduleHandlerProcess process = new ScheduleHandlerProcess();
						process.clientRequest();
					} else if (messageStr.equals(REG_JOB)) {
						ScheduleRecvProcess process = new ScheduleRecvProcess();
						process.clientRequest();
					} else {
						logger.error(this.getClass().getName() + "[messageStr]:" + messageStr + "[Message]:" + message);
					}
				} catch (Exception e) {
					logger.error("프로세스 수행 중 에러 발생. [" + message + "]- " + e.getMessage());
				}

			} catch (IllegalStateException ise) {
				logger.error(name + " IllegalStateException = " + ise.getMessage(), ise);

			} catch (JMSException e) {
				logger.error(name + " JMSException = " + e.getMessage(), e);
				run = false;
			} catch (RuntimeException e) {
				logger.error(name + " RuntimeException = " + e.getMessage(), e);
			}
		}
	}

	public void stop() {
		run = false;
		if (consumer != null)
			try {
				consumer.close();
			} catch (JMSException e) {
			}
		if (session != null)
			try {
				session.close();
			} catch (JMSException e) {
			}
		if (connection != null)
			try {
				connection.close();
			} catch (JMSException e) {
			}
	}

	@Override
	public void onException(JMSException arg0) {
		logger.error("JMS Exception occured.  Shutting down client.");
		stop();
	}
}
