

/********************************************************
	Title : ScheduleLocationIC
	Date  : 23/11/12
	Developer: Kunal Mandhre

 ********************************************************/

package ibase.webitm.ejb.wms;
import ibase.system.config.ConnDriver;
import ibase.webitm.ejb.ValidatorEJB;
import ibase.webitm.utility.GenericUtility;
import ibase.webitm.utility.ITMException;
import java.util.*;
import java.rmi.RemoteException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import javax.ejb.Stateless; 
@Stateless 

public class ScheduleLocationIC extends ValidatorEJB implements ScheduleLocationICLocal, ScheduleLocationICRemote
{
	GenericUtility genericUtility = GenericUtility.getInstance();

	public String wfValData(String xmlString, String xmlString1, String xmlString2, String objContext, String editFlag, String xtraParams) throws RemoteException,ITMException
	{
		String errString = "";
		Document dom = null;
		Document dom1 = null;
		Document dom2 = null;
		System.out.println("xmlString..."+xmlString);
		System.out.println("xmlString1..."+xmlString1);
		System.out.println("xmlString2..."+xmlString2);
		try
		{

			if (xmlString != null && xmlString.trim().length() > 0 )
			{
				dom = parseString(xmlString);
			}
			if (xmlString1 != null && xmlString1.trim().length() > 0 )
			{
				dom1 = parseString(xmlString1);
			}
			if (xmlString2 != null && xmlString2.trim().length() > 0 )
			{
				dom2 = parseString(xmlString2);
			}
			errString = wfValData(dom, dom1, dom2, objContext, editFlag, xtraParams);
		}
		catch(Exception e)
		{
			throw new ITMException(e);
		}
		return(errString);
	}

	public String wfValData(Document dom, Document dom1, Document dom2, String objContext, String editFlag, String xtraParams) throws RemoteException,ITMException
	{
		String locCode = "",siteCode = "",  errCode = "",userId = "",sql = "",updateStatus = "",tranType = "",tranId = "";
		String childNodeName = null;
		String errString = "";
		String errorType = "";
		int count = 0;
		int ctr=0;
		int currentFormNo = 0;
		int childNodeListLength;
		NodeList parentNodeList = null;
		NodeList childNodeList = null;	
		Node parentNode = null;
		Node childNode = null;
		ArrayList<String> errList = new ArrayList<String>();
		ArrayList<String> errFields = new ArrayList<String>();
		Connection conn = null;
		PreparedStatement pstmt = null ;
		ResultSet rs = null;
		ConnDriver connDriver = new ConnDriver();
		StringBuffer errStringXml = new StringBuffer("<?xml version = \"1.0\"?> \r\n <Root> <Errors>"); 
		try
		{
			conn = connDriver.getConnectDB("DriverITM");
			userId = getValueFromXTRA_PARAMS(xtraParams, "loginCode");
			if(objContext != null && objContext.trim().length() > 0)
			{
				currentFormNo = Integer.parseInt(objContext);
			}
			switch(currentFormNo)
			{
			/*case 1 :
				parentNodeList = dom.getElementsByTagName("Detail1");
				parentNode = parentNodeList.item(0);
				childNodeList = parentNode.getChildNodes();
				childNodeListLength = childNodeList.getLength();
				for(ctr = 0; ctr < childNodeListLength; ctr ++)
				{
					childNode = childNodeList.item(ctr);
					childNodeName = childNode.getNodeName();
					if(childNodeName.equalsIgnoreCase("site_code"))
					{

					}
				}
				break;*/
			case 2 :
				parentNodeList = dom.getElementsByTagName("Detail2");
				parentNode = parentNodeList.item(0);
				childNodeList = parentNode.getChildNodes();
				childNodeListLength = childNodeList.getLength();
				for(ctr = 0; ctr < childNodeListLength; ctr ++)
				{
					childNode = childNodeList.item(ctr);
					childNodeName = childNode.getNodeName();
					if(childNodeName.equalsIgnoreCase("loc_code"))
					{
						locCode = checkNull(genericUtility.getColumnValue("loc_code", dom));
						siteCode  = checkNull(genericUtility.getColumnValue("site_code", dom));
						if( locCode.trim().length() == 0)
						{
							errCode = "VMLOC4";
							errList.add(errCode);
							errFields.add(childNodeName.toLowerCase());
						}
						else 
						{
							sql = "select count(*) from location  where loc_code  = ? ";
							pstmt =  conn.prepareStatement(sql);
							pstmt.setString(1,locCode);
							rs = pstmt.executeQuery();
							if(rs.next())
							{
								count =  rs.getInt(1);
							}
							rs.close();
							rs = null;
							pstmt.close();
							pstmt = null;
							if(count == 0) 
							{
								errCode = "VMLOC6";
								errList.add(errCode);
								errFields.add(childNodeName.toLowerCase());
							}
							else
							{

								sql = "select count(*)  from stock where  stock.site_code = ?  and  stock.loc_code = ?      ";
								pstmt =  conn.prepareStatement(sql);
								pstmt.setString(1,siteCode);
								pstmt.setString(2,locCode);
								rs = pstmt.executeQuery();
								if(rs.next())
								{

									count =  rs.getInt(1);
								}
								rs.close();
								rs = null;
								pstmt.close();
								pstmt = null;
								if(count == 0) 
								{
									errCode = "VMIDATA3";
									errList.add(errCode);
									errFields.add(childNodeName.toLowerCase());
								}
							}

						}

					}
					else if(childNodeName.equalsIgnoreCase("tran_type"))
					{
						for(int i =0; i< dom2.getElementsByTagName("Detail2").getLength();i++)
						{
							updateStatus = checkNull(getCurrentUpdateFlag(dom2.getElementsByTagName("Detail2").item(i)));
							System.out.println("line no ="+genericUtility.getColumnValueFromNode("line_no",dom2.getElementsByTagName("Detail2").item(i)));
							tranType =  checkNull(genericUtility.getColumnValueFromNode("tran_type",dom2.getElementsByTagName("Detail2").item(i)));
							System.out.println("Tran Type = "+tranType);
							System.out.println("Update Status = "+updateStatus);
							

							if (updateStatus.equalsIgnoreCase("D") && (tranType == null || tranType.trim().length() == 0))
							{

								errCode = "VMDEL1";
								errList.add(errCode);
								errFields.add(childNodeName.toLowerCase());
							}
							if (updateStatus.equalsIgnoreCase("E") && (tranType == null || tranType.trim().length() == 0)) //added by kunal on 5/12/12
							{
								String locCodeDB = "";
								
								locCode =  checkNull(genericUtility.getColumnValueFromNode("loc_code",dom2.getElementsByTagName("Detail2").item(i)));
								tranId =  checkNull(genericUtility.getColumnValueFromNode("tran_id",dom2.getElementsByTagName("Detail2").item(i)));
								int lineNo = Integer.parseInt(genericUtility.getColumnValueFromNode("line_no",dom2.getElementsByTagName("Detail2").item(i))==null?"0":genericUtility.getColumnValueFromNode("line_no",dom2.getElementsByTagName("Detail2").item(i)));
								sql = "select loc_code  from physcandet where tran_id = ? and line_no = ? ";
								pstmt =  conn.prepareStatement(sql);
								pstmt.setString(1,tranId);
								pstmt.setInt(2,lineNo);
								rs = pstmt.executeQuery();
								if(rs.next())
								{
									locCodeDB =  checkNull(rs.getString(1));
								}
								rs.close();
								rs = null;
								pstmt.close();
								pstmt = null;
								if(!locCodeDB.trim().equalsIgnoreCase(locCode.trim()))
								{
									errCode = "VMDEL2";
									errList.add(errCode);
									errFields.add(childNodeName.toLowerCase());
								}
								
							}
						}
					}

				}
				break;


			}
			int errListSize = errList.size();
			count = 0;
			String errFldName = null;
			if(errList != null && errListSize > 0)
			{
				for(count = 0; count < errListSize; count ++)
				{
					errCode = errList.get(count);
					errFldName = errFields.get(count);
					System.out.println("errCode .........." + errCode);
					errString = getErrorString(errFldName, errCode, userId);
					errorType = errorType(conn , errCode);
					if(errString.length() > 0)
					{
						String bifurErrString = errString.substring(errString.indexOf("<Errors>") + 8, errString.indexOf("<trace>"));
						bifurErrString = bifurErrString + errString.substring(errString.indexOf("</trace>") + 8, errString.indexOf("</Errors>"));
						errStringXml.append(bifurErrString);
						errString = "";
					}
					if(errorType.equalsIgnoreCase("E"))
					{
						break;
					}
				}
				errList.clear();
				errList = null;
				errFields.clear();
				errFields = null;
				errStringXml.append("</Errors> </Root> \r\n");
			}
			else
			{
				errStringXml = new StringBuffer("");
			}
		}
		catch(Exception e)
		{
			e.printStackTrace();
			errString = e.getMessage();
			throw new ITMException(e);
		}
		finally
		{
			try
			{
				if(conn != null)
				{
					if(rs != null) 
					{
						rs.close();
						rs = null;
					}
					if(pstmt != null) 
					{
						pstmt.close();
						pstmt = null;
					}
					conn.close();
				}
				conn = null;
			} 
			catch(Exception d)
			{
				d.printStackTrace();
				throw new ITMException(d);
			}
		}
		errString = errStringXml.toString();
		return errString;
	}//end of validation

	// method for item change
	public String itemChanged(String xmlString, String xmlString1, String xmlString2, String objContext, String currentColumn, String editFlag, String xtraParams) throws RemoteException, ITMException
	{
		Document dom = null;
		Document dom1 = null;
		Document dom2 = null;
		String valueXmlString = "";
		System.out.println("xmlString............."+xmlString);
		System.out.println("xmlString1............"+xmlString1);
		System.out.println("xmlString2............"+xmlString2);
		try
		{   
			if(xmlString != null && xmlString.trim().length() > 0)
			{
				dom = parseString(xmlString);
			}
			if(xmlString1 != null && xmlString1.trim().length() > 0)
			{
				dom1 = parseString(xmlString1);
			}
			if(xmlString2 != null && xmlString2.trim().length() > 0)
			{
				dom2 = parseString(xmlString2);
			}
			valueXmlString = itemChanged(dom, dom1, dom2, objContext, currentColumn, editFlag, xtraParams);
		}
		catch(Exception e)
		{
			System.out.println("Exception : [ScheduleLocationIC][itemChanged( String, String )] :==>\n" + e.getMessage());
			throw new ITMException(e);
		}
		return valueXmlString;
	}

	// method for item change
	public String itemChanged(Document dom, Document dom1, Document dom2, String objContext, String currentColumn, String editFlag, String xtraParams) throws RemoteException, ITMException
	{
		String itemDescr = "",locDescr = "" ,siteDescr = "",itemCode = "",locCode = "",sql = "",siteCode = "";
		String analysisClass = "", cycleCriteria = "",lotNo = "",lotsl = "",unit = "",tranId = "",empCode = "",empName = "";
		String childNodeName = null;
		StringBuffer valueXmlString = new StringBuffer();
		int ctr = 0, currentFormNo = 0, childNodeListLength = 0,maxprioritySeq = 0,prioritySeq = 0;
		double quantity = 0;
		NodeList parentNodeList = null;
		NodeList childNodeList = null;
		Node parentNode = null;
		Node childNode = null;
		Connection conn = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null ;
		GenericUtility genericUtility = GenericUtility.getInstance();
		ConnDriver connDriver = new ConnDriver();
		try
		{   
			conn = connDriver.getConnectDB("DriverITM");
			conn.setAutoCommit(false);
			connDriver = null;
			empCode =  genericUtility.getValueFromXTRA_PARAMS( xtraParams, "loginEmpCode");
			if(objContext != null && objContext.trim().length() > 0)
			{
				currentFormNo = Integer.parseInt(objContext);
			}
			valueXmlString = new StringBuffer("<?xml version = \"1.0\"?> <Root> <header> <editFlag>");
			valueXmlString.append(editFlag).append("</editFlag> </header>");
			switch(currentFormNo)
			{

			case 1 : 
				parentNodeList = dom.getElementsByTagName("Detail1");
				parentNode = parentNodeList.item(0);
				childNodeList = parentNode.getChildNodes();
				valueXmlString.append("<Detail1>");
				childNodeListLength = childNodeList.getLength();
				do
				{   
					childNode = childNodeList.item(ctr);
					childNodeName = childNode.getNodeName();
					ctr ++;
				}while(ctr < childNodeListLength  && ! childNodeName.equals(currentColumn));


				if(currentColumn.trim().equalsIgnoreCase("itm_defaultedit")) //added by kunal on 5/12/12
				{
					System.out.println("emp code = "+empCode);
					sql = " select emp_fname  from employee where emp_code = ?  ";
					pstmt =  conn.prepareStatement(sql);
					pstmt.setString(1,empCode);
					rs = pstmt.executeQuery();
					if(rs.next())
					{
						empName = rs.getString(1);
					}
					rs.close();
					rs = null;
					pstmt.close();
					pstmt = null;
					
					valueXmlString.append("<emp_code__user>").append("<![CDATA[" + empCode +"]]>").append("</emp_code__user>");
					valueXmlString.append("<employee_emp_fname>").append("<![CDATA[" + empName +"]]>").append("</employee_emp_fname>");
					
				}
				valueXmlString.append("</Detail1>");
				break; 
			case 2 : 
				parentNodeList = dom.getElementsByTagName("Detail2");
				parentNode = parentNodeList.item(0);
				childNodeList = parentNode.getChildNodes();
				valueXmlString.append("<Detail2>");
				childNodeListLength = childNodeList.getLength();
				do
				{   
					childNode = childNodeList.item(ctr);
					childNodeName = childNode.getNodeName();
					ctr ++;
				}while(ctr < childNodeListLength  && ! childNodeName.equals(currentColumn));


				if(currentColumn.trim().equalsIgnoreCase("itm_default"))
				{
					siteCode  = checkNull(genericUtility.getColumnValue("site_code", dom1));
					tranId  = checkNull(genericUtility.getColumnValue("tran_id", dom1));
					sql = "Select descr  from site where site_code = ?";
					pstmt =  conn.prepareStatement(sql);
					pstmt.setString(1,siteCode);
					rs = pstmt.executeQuery();
					if(rs.next())
					{
						siteDescr = rs.getString(1);
					}
					rs.close();
					rs = null;
					pstmt.close();
					pstmt = null;
					valueXmlString.append("<site_code>").append("<![CDATA[" + siteCode +"]]>").append("</site_code>");
					valueXmlString.append("<site_descr>").append("<![CDATA[" + siteDescr +"]]>").append("</site_descr>");
					/*sql = "select max(priority_seq) from physcandet where tran_id = ? ";
					pstmt =  conn.prepareStatement(sql);
					pstmt.setString(1,tranId);
					rs = pstmt.executeQuery();
					if(rs.next())
					{
						maxprioritySeq = rs.getInt(1);
					}
					rs.close();
					rs = null;
					pstmt.close();
					pstmt = null;*/
					NodeList parentNodeList1 = null;
					int parentNodeListLength = 0;
					parentNodeList1 = dom2.getElementsByTagName("Detail2");
					parentNodeListLength = parentNodeList1.getLength();
					for(int i = 0; i < parentNodeListLength ; i++ )
					{
						System.out.println("TEST LENGTH="+parentNodeListLength);
						parentNode = parentNodeList.item(i);
						prioritySeq = Integer.parseInt(genericUtility.getColumnValueFromNode("priority_seq",dom2.getElementsByTagName("Detail2").item(i))== null?"0":genericUtility.getColumnValueFromNode("priority_seq",dom2.getElementsByTagName("Detail2").item(i)));
						//System.out.println("line no ="+genericUtility.getColumnValueFromNode("line_no",dom2.getElementsByTagName("Detail2").item(i)));
						//System.out.println("loc_code ="+genericUtility.getColumnValueFromNode("loc_code",dom2.getElementsByTagName("Detail2").item(i)));
						//prioritySeq = Integer.parseInt(genericUtility.getColumnValue("priority_seq", dom)==null?"0":genericUtility.getColumnValue("priority_seq", dom));
						System.out.println("Max Seq ="+maxprioritySeq+"   seq="+prioritySeq);
						if(prioritySeq > maxprioritySeq)
						{
							maxprioritySeq = prioritySeq; 
						}

					}
					System.out.println("maxprioritySeq = "+maxprioritySeq);
					maxprioritySeq++;
					System.out.println("maxprioritySeq new = "+maxprioritySeq);
					valueXmlString.append("<priority_seq>").append("<![CDATA[" + maxprioritySeq +"]]>").append("</priority_seq>");
					valueXmlString.append("<emp_code__user>").append("<![CDATA[" + empCode +"]]>").append("</emp_code__user>");


				}
				else if(currentColumn.trim().equalsIgnoreCase("itm_defaultedit"))
				{
					System.out.println("INSIDE ITM_DEFAULTEDIT");
					valueXmlString.append("<emp_code__user>").append("<![CDATA[" + empCode +"]]>").append("</emp_code__user>");
				}
				else if(currentColumn.trim().equalsIgnoreCase("loc_code"))
				{
					System.out.println("loc code ic ");
					locCode  = checkNull(genericUtility.getColumnValue("loc_code", dom));
					siteCode  = checkNull(genericUtility.getColumnValue("site_code", dom));
					System.out.println("site code= "+siteCode);
					System.out.println("loc code ="+locCode);

					if(locCode != null && locCode.trim().length() > 0)
					{
						sql = "select stock.item_code,stock.quantity,stock.unit,stock.lot_no,stock.lot_sl,location.descr,item.descr,item.analysis_class,item.cycle_criteria "
								+" from stock,location,item  where  stock.loc_code = location.loc_code and stock.item_code = item.item_code "
								+" and stock.site_code = ?  and  stock.loc_code = ?    ";
						pstmt =  conn.prepareStatement(sql);
						pstmt.setString(1,siteCode);
						pstmt.setString(2,locCode);
						rs = pstmt.executeQuery();
						if(rs.next())
						{

							itemCode = rs.getString("item_code");
							quantity = rs.getDouble("quantity");
							unit = rs.getString("unit");
							lotNo = rs.getString("lot_no");
							lotsl = rs.getString("lot_sl");
							locDescr = rs.getString(6);
							itemDescr = rs.getString(7);
							analysisClass = rs.getString("analysis_class");
							cycleCriteria = rs.getString("cycle_criteria");

						}
						rs.close();
						rs = null;
						pstmt.close();
						pstmt = null;
					}
					valueXmlString.append("<location_descr>").append("<![CDATA[" + locDescr +"]]>").append("</location_descr>");
					valueXmlString.append("<item_code>").append("<![CDATA[" + itemCode +"]]>").append("</item_code>");
					valueXmlString.append("<item_descr>").append("<![CDATA[" + itemDescr +"]]>").append("</item_descr>");
					valueXmlString.append("<lot_no>").append("<![CDATA[" + lotNo +"]]>").append("</lot_no>");
					valueXmlString.append("<lot_sl>").append("<![CDATA[" + lotsl +"]]>").append("</lot_sl>");
					valueXmlString.append("<quantity>").append("<![CDATA[" + quantity +"]]>").append("</quantity>");
					valueXmlString.append("<unit>").append("<![CDATA[" + unit +"]]>").append("</unit>");
					valueXmlString.append("<analysis_class>").append("<![CDATA[" + analysisClass +"]]>").append("</analysis_class>");
					valueXmlString.append("<cycle_criteria>").append("<![CDATA[" + cycleCriteria +"]]>").append("</cycle_criteria>");

				}
				valueXmlString.append("</Detail2>");
				break;
			}
			valueXmlString.append("</Root>");
			System.out.println("XML STRING ="+valueXmlString);
		}
		catch(Exception e)
		{
			e.printStackTrace();
			System.out.println("Exception ::"+ e.getMessage());
			throw new ITMException(e);
		}
		finally
		{
			try
			{
				if(conn != null)
				{
					if(rs != null) 
					{
						rs.close();
						rs = null;
					}
					if(pstmt != null) 
					{
						pstmt.close();
						pstmt = null;

					}
					conn.close();
				}
				conn = null;	
			}
			catch(Exception e)
			{
				e.printStackTrace();
				throw new ITMException(e);
			}			
		}
		return valueXmlString.toString();
	}
	private String checkNull(String input) 
	{
		if(input == null)
		{
			input = "";
		}
		return input;
	}
	private String getCurrentUpdateFlag(Node currDetail)
	{
		NodeList currDetailList = null;
		String updateStatus = "",nodeName = "";
		int currDetailListLength = 0;

		currDetailList = currDetail.getChildNodes();
		currDetailListLength = currDetailList.getLength();
		for (int i=0;i< currDetailListLength;i++)
		{
			nodeName = currDetailList.item(i).getNodeName();
			if (nodeName.equalsIgnoreCase("Attribute"))
			{
				updateStatus =currDetailList.item(i).getAttributes().getNamedItem("updateFlag").getNodeValue();
				break;
			}
		}
		return updateStatus;
	}


	private String errorType(Connection conn , String errorCode) throws ITMException
	{
		String msgType = "";
		PreparedStatement pstmt = null ; 
		ResultSet rs = null;
		try
		{			
			String  sql = "SELECT MSG_TYPE FROM MESSAGES WHERE MSG_NO = ?";
			pstmt = conn.prepareStatement(sql);			
			pstmt.setString(1,errorCode);			
			rs = pstmt.executeQuery();
			while(rs.next())
			{
				msgType = rs.getString("MSG_TYPE");
			}			
		}
		catch(Exception ex)
		{
			ex.printStackTrace();
			throw new ITMException(ex);
		}		
		finally
		{
			try
			{
				if(rs != null)
				{
					rs.close();
					rs = null;
				}
				if(pstmt != null)
				{
					pstmt.close();
					pstmt = null;
				}
			}
			catch(Exception e)
			{
				e.printStackTrace();
				throw new ITMException(e);
			}
		}		
		return msgType;
	}
}	
