package com.cim.idm.wmsextend.generic.util;

import com.cim.idm.framework.IDMFrameServiceProxy;
import com.cim.idm.framework.util.xml.JdomUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jdom.Document;
import org.jdom.Element;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.SqlParameter;
import org.springframework.jdbc.core.support.SqlLobValue;
import org.springframework.jdbc.object.SqlUpdate;
import org.springframework.jdbc.support.lob.DefaultLobHandler;

import java.io.StringReader;
import java.sql.Types;

public class MessageHistoryUtil {
	private static Log log = LogFactory.getLog(MessageHistoryUtil.class);
	/**
	 * @uml.property  name="lobHandler"
	 * @uml.associationEnd  multiplicity="(1 1)"
	 */
	private DefaultLobHandler lobHandler = new DefaultLobHandler();
	/*
	* Name : setMessageHistory
	* Desc : This function is setMessageHistory
	* Author : ZXY Systems, Inc
	* Date : 2013.01.19
	*/
	public void setMessageHistory (String serverName, Document xml) {
		String messageName = "";
		//String transactionId = "";
		//String replySubjectName = "";

		String lotName = "";
		String carrierName = "";
		String machineName = "";
		String portName = "";
		String productSpecName = "";
		String processOperationName = "";
		String eventUser = "";
		String fullMessage = JdomUtils.toString(xml);
		
		byte[] byteStr = fullMessage.getBytes();
		if (byteStr.length > 4000)
		{
			fullMessage = new String(byteStr, 0, 3900);
		}

		try
		{
			Element root = xml.getDocument().getRootElement();
	
			Element elementHeader = root.getChild("header");
			Element elementBody = root.getChild("body");
			if ( elementHeader != null )
			{
				if (elementHeader.getChild("messagename") != null) { messageName = elementHeader.getChild("messagename").getText();	}
				if ( elementBody != null)
				{
					if (elementBody.getChild("LOTNAME") != null) { lotName = elementBody.getChild("LOTNAME").getText(); }
					if (elementBody.getChild("CARRIERNAME") != null) { carrierName = elementBody.getChild("CARRIERNAME").getText();	}
					if (elementBody.getChild("MACHINENAME") != null) { machineName = elementBody.getChild("MACHINENAME").getText(); } 
					if (elementBody.getChild("PORTNAME") != null) { portName = elementBody.getChild("PORTNAME").getText(); }
					if (elementBody.getChild("PRODUCTSPECNAME") != null) {productSpecName = elementBody.getChild("PRODUCTSPECNAME").getText(); }
					if (elementBody.getChild("PROCESSOPERATIONNAME") != null) {processOperationName = elementBody.getChild("PROCESSOPERATIONNAME").getText(); }
					if (elementBody.getChild("EVENTUSER") != null) {eventUser = elementBody.getChild("EVENTUSER").getText(); }
				}
			}
			else
			{
				return;
			}
	
			try
			{
				
				String sql = "SELECT RECEIVEFLAG, EXPLICITCOMMIT FROM BSMESSAGEDEF WHERE SERVERNAME = ? AND MESSAGENAME = ?";
				String[] bindSet = new String[] {serverName, messageName};

				String[][] sqlResult = IDMFrameServiceProxy.getSqlTemplate().queryForStringArray(sql, bindSet);
				
				if(sqlResult.length == 0 || sqlResult[0][0].equals("Y"))
				{
					String expliciCommit = "";
					if (sqlResult.length > 0) {	expliciCommit = sqlResult[0][1].toString(); }
					
					sql = "INSERT INTO BSMESSAGEHISTORY (SERVERNAME, MESSAGENAME, TIMEKEY, LOTNAME, CARRIERNAME, MACHINENAME, PORTNAME, PRODUCTSPECNAME, PROCESSOPERATIONNAME, EVENTUSER, FULLMESSAGE) " +
					 "VALUES ( ?, ?, TO_CHAR(SYSTIMESTAMP, 'YYYYMMDDHH24MISSFF6'), ?, ?, ?, ?, ?, ?, ?, ? )";				
					/*
					JdbcTemplate jdbcTemplate = IDMFrameServiceProxy.getSqlTemplate().getJdbcTemplate();
					jdbcTemplate = IDMFrameServiceProxy.getSqlTemplate().getJdbcTemplate();

					Object[] objects = new Object[] {serverName, messageName, lotName, carrierName, machineName, portName, productSpecName, processOperationName, eventUser, fullMessage};
					
					jdbcTemplate.update(sql, objects);
					*/
					JdbcTemplate jdbcTemplate = IDMFrameServiceProxy.getSqlTemplate().getJdbcTemplate();
					SqlUpdate sqlUpdate = new SqlUpdate(jdbcTemplate.getDataSource(), sql);
					sqlUpdate.declareParameter(new SqlParameter(Types.VARCHAR));
					sqlUpdate.declareParameter(new SqlParameter(Types.VARCHAR));
					sqlUpdate.declareParameter(new SqlParameter(Types.VARCHAR));
					sqlUpdate.declareParameter(new SqlParameter(Types.VARCHAR));
					sqlUpdate.declareParameter(new SqlParameter(Types.VARCHAR));
					sqlUpdate.declareParameter(new SqlParameter(Types.VARCHAR));
					sqlUpdate.declareParameter(new SqlParameter(Types.VARCHAR));
					sqlUpdate.declareParameter(new SqlParameter(Types.VARCHAR));
					sqlUpdate.declareParameter(new SqlParameter(Types.VARCHAR));
					sqlUpdate.declareParameter(new SqlParameter(Types.CLOB));
					Object objFullMessage = new SqlLobValue(new StringReader(fullMessage),fullMessage.length(),lobHandler);
					sqlUpdate.compile();
					
					Object[] objects = new Object[] {serverName, messageName, lotName, carrierName, machineName, portName, productSpecName, processOperationName, eventUser, objFullMessage};
					
					sqlUpdate.update(objects);
					if (!expliciCommit.equals("N"))
					{
						jdbcTemplate.update("commit");
					}
				}
			}
			catch (Exception e)
			{
				//log.error("ERP Interface Error : " + e.getMessage());
				log.error("Error MessageHistory : " + e.getMessage());

			}
		}
		catch (Exception e)	
		{
			
		}
		
	}
}