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.common.CommonKeys;
import com.eactive.eai.batch.doc.BatchDoc;
import com.eactive.eai.batch.job.jobComm.OutboundFTPHandle;
import com.eactive.eai.batch.job.jobComm.OutboundSocketHandle;
import com.eactive.eai.batch.job.jobHandle.JobFinishHandler;
import com.eactive.eai.batch.message.EAIBatchMsgManager;
import com.eactive.eai.common.exception.ExceptionUtil;
import com.eactive.eai.common.util.DatetimeUtil;
import com.eactive.eai.common.util.Logger;

public class JobHandlerConsumer  implements Runnable, ExceptionListener {
	
	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 JobHandlerConsumer(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() {
		BatchDoc batchDoc = null;
		while(run) {
			try {
				 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 {
					 batchDoc = (BatchDoc)omsg.getObject();
		        } catch(Exception e) {
		            throw new RuntimeException(name+" Invlid value object in ObjectMessage. - "+e.getMessage() );
		        }
			 
			        //LayerCode, SubLayerCode 설정
					EAIBatchMsgManager.updateBatchMsg(batchDoc, CommonKeys.LAYER_FLOW_CONTROLLER, CommonKeys.SUB_LAYER_FLOW_CONTROLLER);
			        batchDoc.getBatchMsg().getBody().setPhaseStartTime(DatetimeUtil.getCurrentTimeMillis());

			        try {
			        	if ( batchDoc.getBatchMsg().getHeader().getRuleCode().startsWith("FTP") ){
			        		OutboundFTPHandle handle = new OutboundFTPHandle();
			        		handle.proc(batchDoc);
			        	}else{
			        		OutboundSocketHandle handle = new OutboundSocketHandle();
			        		handle.proc(batchDoc);
			        	}
					} catch (Exception ex) {
						try {
				            // 파일로그 처리
				            String errMsg = ExceptionUtil.getErrorCode(ex, "BECEAIFJH007");
				            logger.error(errMsg, ex);

				            // DB로그 처리
							new JobFinishHandler(batchDoc).handleErrorEnd(errMsg);

						} catch (Exception e2) {
							logger.error("★★★★★ JobHandler JPD 예외 처리 중 에러 !! ★★★★★", e2);
						}
					}
			} 
			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();
	}
}
