/********************************************************
	Title : WoFirmplanIC
	Date  : 15/10/14
	Developer: manohar

 ********************************************************/
package ibase.webitm.ejb.mfg;
import ibase.system.config.ConnDriver;
import ibase.webitm.ejb.ValidatorEJB;
import ibase.webitm.utility.GenericUtility;
import ibase.webitm.utility.ITMException;

import java.text.SimpleDateFormat;
import java.util.*;
import java.rmi.RemoteException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;

import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;


import javax.ejb.Stateless; 
@Stateless 

public class WoFirmplanIC extends ValidatorEJB implements WoFirmplanICLocal, WoFirmplanICRemote
{
	GenericUtility genericUtility = GenericUtility.getInstance();

	public String wfValData(String xmlString, String xmlString1, String objContext, String editFlag, String xtraParams) throws RemoteException,ITMException
	{
		String errString = "";
		Document dom = null;
		Document dom1 = null;
		try
		{
			if (xmlString != null && xmlString.trim().length() > 0 )
			{
				dom = parseString(xmlString);
				System.out.println("xmlString["+xmlString+"]");
			}
			if (xmlString1 != null && xmlString1.trim().length() > 0 )
			{
				dom1 = parseString(xmlString1);
				System.out.println("xmlString1["+xmlString1+"]");
			}
			
			errString = wfValData(dom, dom1, objContext, editFlag, xtraParams);
		}
		catch(Exception e)
		{
			System.out.println("Exception : [Firmplan][wfValData( String, String )] :==>\n" + e.getMessage());
			throw new ITMException(e);
		}
		return(errString);
	}
	public String wfValData(Document dom, Document dom1, String objContext, String editFlag, String xtraParams) throws RemoteException,ITMException
	{
			String childNodeName = null;
			String errString = "";
			String errCode = "";
			String userId = "";
			String sql = "";
			String errorType = "";
			int cnt = 0,cnt1= 0;
			int ctr=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>");
			
			int currentFormNo =0,recCnt=0,recCnt1=0;
			
			String bomcode="",amdNo="",lineNo="";
			String active = "",confirmed = "";
			String bomcodeHdr = "",lineNoBOM = "",updateStatus="",supMfgCode="",itemCode="";
			String supCode="",supMfgCodeList[]=null;
			String loginSiteCode="",siteCode="";
			try
			{
				System.out.println("@@@@@@@@ wfvaldata called");
				conn = connDriver.getConnectDB("DriverITM");
				connDriver = null;
				userId = getValueFromXTRA_PARAMS(xtraParams,"loginCode");
				loginSiteCode = checkNull(genericUtility.getValueFromXTRA_PARAMS(xtraParams, "loginSiteCode"));
				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("bom_code"))
						{    
							bomcode = checkNull(genericUtility.getColumnValue("bom_code", dom));

							loginSiteCode = checkNull(genericUtility.getColumnValue("site_code", dom));
							System.out.println("@@loginSiteCode"+loginSiteCode);
							System.out.println("@@@@ bom_code["+bomcode+"]");
							if(bomcode == null || bomcode.trim().length() == 0)
							{
								errCode = "VTINVBOM1";
								errList.add(errCode);
								errFields.add(childNodeName.toLowerCase());
							}
							else
							{	
								
								errCode = isExist("bom","bom_code",bomcode,conn);
								if( "FALSE".equalsIgnoreCase(errCode ))		
								{
									errCode = "VTBOMCD3";
									errList.add(errCode);
									errFields.add(childNodeName.toLowerCase());
								}
								else
								{									
								
								sql = "	select site_code from bom where bom_code = ?  ";
								pstmt =  conn.prepareStatement(sql);
								pstmt.setString(1,bomcode);
								rs = pstmt.executeQuery();
								if(rs.next())
								{   
									
									siteCode = rs.getString("site_code")==null?"":rs.getString("site_code");;
								}
								rs.close();
								rs = null;
								pstmt.close();
								pstmt = null;
								 
								if(siteCode.trim().length() > 0 && siteCode != null)
								{
									sql = "	select confirmed from bom where bom_code = ? and site_code=? ";
									pstmt =  conn.prepareStatement(sql);
									pstmt.setString(1,bomcode);
									pstmt.setString(2,loginSiteCode);
									rs = pstmt.executeQuery();
									if(rs.next())
									{   
										recCnt++;
										confirmed = rs.getString("confirmed")==null?"N":rs.getString("confirmed");
										
									}
									rs.close();
									rs = null;
									pstmt.close();
									pstmt = null;
									if( recCnt == 0 )
									{
										errCode = "VTBOMCD4";
										errList.add(errCode);
										errFields.add(childNodeName.toLowerCase());
									}
								}
								else
								{	
									sql = "	select confirmed from bom where bom_code = ? ";
									pstmt =  conn.prepareStatement(sql);
									pstmt.setString(1,bomcode);
									rs = pstmt.executeQuery();
									if(rs.next())
									{   
										confirmed = rs.getString("confirmed")==null?"N":rs.getString("confirmed");
										
									}
									rs.close();
									rs = null;
									pstmt.close();
									pstmt = null;
									
								}
						
								
								if (!("Y".equalsIgnoreCase(confirmed)) )
									{
										errCode = "VTNOTCONF1";
										errList.add(errCode);
										errFields.add(childNodeName.toLowerCase());
	
									}	
									
								}
							}
						}
						
					}// end for
					break;  // case 1 end
	
				case 2:
					parentNodeList = dom.getElementsByTagName("Detail2");
					parentNode = parentNodeList.item(0);
					childNodeList = parentNode.getChildNodes();
					childNodeListLength = childNodeList.getLength();
					System.out.println("@@@@@@@@@@@@childNodeListLength["+childNodeListLength+"]");
					for(ctr = 0; ctr < childNodeListLength; ctr++)
					{
						childNode = childNodeList.item(ctr);
						childNodeName = childNode.getNodeName();
						if(childNodeName.equalsIgnoreCase("bom_code"))
						{
							bomcode = checkNull(genericUtility.getColumnValue("bom_code", dom));
							bomcodeHdr = checkNull(genericUtility.getColumnValue("bom_code", dom1));
							System.out.println("@@@@ bomcode["+bomcode+"]::::bomcodeHdr["+bomcodeHdr+"]");
							
						} if (childNodeName.equalsIgnoreCase("supp_code__mfg"))
						{
							supMfgCode=checkNull(this.genericUtility.getColumnValue("supp_code__mfg", dom));
							itemCode=checkNull(this.genericUtility.getColumnValue("item_code", dom));
							System.out.println(">>>>>>>>>>>>>>supMfgCode for validation:"+supMfgCode);
							System.out.println(">>>>>>>>>>>>>>itemCode for validation:"+itemCode);
							if (supMfgCode == null || supMfgCode.trim().length()==0)
							{
								sql = "SELECT count(*) AS cnt FROM siteitem WHERE site_code=? AND item_code=? AND CASE WHEN appr_supp IS NULL THEN 'N' ELSE appr_supp END ='Y' ";
								pstmt = conn.prepareStatement(sql);
								pstmt.setString(1, loginSiteCode);
								pstmt.setString(2, itemCode);
								
								rs = pstmt.executeQuery();
								if(rs.next())
								{
									cnt = rs.getInt("cnt");
								}
								rs.close();
								rs = null;
								pstmt.close();
								pstmt = null;	
								System.out.println(">>>>>>>>>>>>>>cnt validation:"+cnt);
								if(cnt > 0)
								{
									errCode = "VTAPRSUPP";
									errList.add(errCode);
									errFields.add(childNodeName.toLowerCase());
									
								}
								
							}
							
							//check validation for supp_code__mfg not null
							if (supMfgCode != null && supMfgCode.trim().length()>0 && errCode.trim().length()==0 )
							{
								supMfgCode=supMfgCode.trim();
								System.out.println(">>>>>>>>>>>>> supMfgCode not null:" + supMfgCode.toString());
								supMfgCodeList = supMfgCode.split(",");
								if (supMfgCodeList != null && supMfgCodeList.length > 0)
								{
									for(int i=0; supMfgCodeList.length>i; i++)
									{
										supCode="";
										supCode = supMfgCodeList[i];
										System.out.println(">>>>>>>>>>>>>>> found supCode:" + supCode);
										sql = "SELECT count(*) AS cnt FROM supplier WHERE supp_code =? ";
										pstmt = conn.prepareStatement(sql);
										pstmt.setString(1, supCode.trim());
										rs = pstmt.executeQuery();
										if(rs.next())
										{
											cnt = rs.getInt("cnt");
										}
										rs.close();
										rs = null;
										pstmt.close();
										pstmt = null;
							            System.out.println(">>>>>>>>>>>>>>cnt for supCode:"+cnt);
										if(cnt==0)
										{
											errCode = "VMSUPP1";
											errList.add(errCode);
											errFields.add(childNodeName.toLowerCase());
											
										}
										
									} //end for loop for split supp code
									
								}
								
							} 
						
						}//validation end for supp_code__mfg 
						


						if ( childNodeName.equalsIgnoreCase("line_no__bom"))
						{
								lineNoBOM = checkNull(genericUtility.getColumnValue("line_no__bom", dom));
								bomcode = checkNull(genericUtility.getColumnValue("bom_code", dom));
								lineNo = checkNull(genericUtility.getColumnValue("line_no", dom));
								System.out.println("@@@@@@lineNoBOM["+lineNoBOM+"]"+"bomcode["+bomcode+"]");	

								if(lineNoBOM == null || lineNoBOM.trim().length() == 0)
								{
									errCode = "VTLINEBLK1";
									errList.add(errCode);
									errFields.add(childNodeName.toLowerCase());
								}
								else if( lineNoBOM != null && lineNoBOM.length() > 0 )	
								{
								sql = "select count(1) from bomdet where bom_code   = ? and line_no = ? ";
								pstmt =  conn.prepareStatement(sql);
								pstmt.setString(1,bomcode);
								pstmt.setString(2,lineNoBOM);
								rs = pstmt.executeQuery();
								if(rs.next())
								{
									cnt = rs.getInt(1);
								}
								rs.close();
								rs = null;
								pstmt.close();
								pstmt = null;

								if( cnt == 0 )
								{
									errCode = "VTBOMDTLN2";										
									errList.add(errCode);
									errFields.add(childNodeName.toLowerCase());
								}
								else
								{ 		
											java.util.HashSet<String> bomData=new java.util.HashSet<String>();
											for(int i =0; i< dom2.getElementsByTagName("Detail2").getLength();i++)
											{
												updateStatus = checkNull(getCurrentUpdateFlag(dom2.getElementsByTagName("Detail2").item(i)));
												System.out.println("lineno ="+genericUtility.getColumnValueFromNode("line_no",dom2.getElementsByTagName("Detail2").item(i)));
												bomcode =  checkNull(genericUtility.getColumnValueFromNode("bom_code",dom2.getElementsByTagName("Detail2").item(i)));
												lineNoBOM =  checkNull(genericUtility.getColumnValueFromNode("line_no__bom",dom2.getElementsByTagName("Detail2").item(i)));
												System.out.println("bomcode = ["+bomcode+"]"+"Update Status =[ "+updateStatus+"]"+"lineNoBOM["+lineNoBOM+"]");
																											
												if(!updateStatus.equalsIgnoreCase("D"))
												{								
													if ( ! bomData.contains(bomcode.trim()+"@"+lineNoBOM.trim()))
													{
														bomData.add(bomcode.trim()+"@"+lineNoBOM.trim());										
													}
													else
													{	errCode = "VTDUPBOMLN";
													errList.add(errCode);
													errFields.add(childNodeName.toLowerCase());
													}										
													System.out.println("bomData LIST["+bomData+"]");
												}
											}
										
									}
								}
						}
							
						
					} // end for
					break;  // case 1 end
	
				
	
				}*/
	
				int errListSize = errList.size();
				cnt = 0;
				String errFldName = null;
				if(errList != null && errListSize > 0)
				{
					for(cnt = 0; cnt < errListSize; cnt ++)
					{
						errCode = errList.get(cnt);
						errFldName = errFields.get(cnt);
						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 objContext, String currentColumn, String editFlag, String xtraParams) throws RemoteException, ITMException
	{
		Document dom = null;
		Document dom1 = null;
		String valueXmlString = "";
		System.out.println("xmlString.............["+xmlString + "]");
		System.out.println("xmlString1............["+xmlString1 + "]");
		try
		{   
			if(xmlString != null && xmlString.trim().length() > 0)
			{
				dom = parseString(xmlString);
			}
			if(xmlString1 != null && xmlString1.trim().length() > 0)
			{
				dom1 = parseString(xmlString1);
			}
			valueXmlString = itemChanged(dom, dom1, objContext, currentColumn, editFlag, xtraParams);
		}
		catch(Exception e)
		{
			System.out.println("Exception : [RoadPermitIC][itemChanged( String, String )] :==>\n" + e.getMessage());
			throw new ITMException(e);
		}
		return valueXmlString;
	}


	// method for item change
	public String itemChanged(Document dom, Document dom1, String objContext, String currentColumn, String editFlag, String xtraParams) throws RemoteException, ITMException
	{
	String childNodeName = null;
	String sql = "",amdNo="";
	StringBuffer valueXmlString = new StringBuffer();
	int ctr = 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();
	
	int currentFormNo =0;
	String columnValue="",workOrder = "",campgnNo = "";
	String unit="",unitpotency="",loginSiteCode="";
	
	String linenobom="",itemref="",unitalt="",matchpoten="",adjpotency="",qtyperunit="";
	String criticalitem="",supcodemfg="",mfgref="",issvariencetype="",issvarvaltype="",locusagetype="";
	double minpotency =0,minqty=0,qtyper=0,qtyperalt=0,leadtime=0,conqty=0,maxbatchqty=0,minbatchqty=0,batchqty=0;
	double issVarience = 0;
	
	Timestamp validupto=null;
	
	
	try
	{
		Calendar currentDate = Calendar.getInstance();
		SimpleDateFormat sdf = new SimpleDateFormat(genericUtility.getApplDateFormat());
		String sysDate = sdf.format(currentDate.getTime());
		System.out.println("Now the date is :=>  " + sysDate);

		conn = connDriver.getConnectDB("DriverITM");
		conn.setAutoCommit(false);
		connDriver = null;

		if(objContext != null && objContext.trim().length()>0)
		{
			currentFormNo = Integer.parseInt(objContext.trim());
		}

		valueXmlString = new StringBuffer("<?xml version = \"1.0\"?> <Root> <header> <editFlag>");
		valueXmlString.append(editFlag).append("</editFlag> </header>");

		System.out.println("**********ITEMCHANGE FOR CASE"+currentFormNo+"**************");
		switch(currentFormNo)
		{
		case 1 :
			parentNodeList = dom.getElementsByTagName("Detail1");
			parentNode = parentNodeList.item(0);
			childNodeList = parentNode.getChildNodes();
			ctr = 0; 
			valueXmlString.append("<Detail1>");
			int childNodeListLength = childNodeList.getLength();
			do
			{ 
				childNode = childNodeList.item(ctr);
				childNodeName = childNode.getNodeName();
				if(childNodeName.equals(currentColumn))
				{
					if (childNode.getFirstChild()!= null)
					{
						columnValue = childNode.getFirstChild().getNodeValue().trim();
					}
				}
				ctr++;
			}
			while(ctr < childNodeListLength  && !childNodeName.equals(currentColumn));
			System.out.println(" Itemchanged called for [" + currentColumn + "] ==> [" + columnValue + "]");
			/*if(currentColumn.trim().equalsIgnoreCase("itm_defaultedit"))
			{	
				campgnNo = checkNull(genericUtility.getColumnValue("campaign_no", dom));
				
				valueXmlString.append("<bom_code protect = \"1\">").append("<![CDATA["+bomcode+"]]>").append("</bom_code>");
								
			}
			else*/ if(currentColumn.trim().equalsIgnoreCase("itm_default"))
			{
				campgnNo = checkNull(genericUtility.getColumnValue("campgn_no", dom));
				workOrder = checkNull(genericUtility.getColumnValue("work_order", dom));
				System.out.println(" Itemchanged called for [" + currentColumn + "] ==> [" + columnValue + "] campgnNo [" + campgnNo + "] workOrder [" + workOrder + "]");
				if ( campgnNo != null && !"null".equals(campgnNo) && campgnNo.trim().length() > 0  )
				{
					valueXmlString.append("<work_order protect = \"1\">").append("<![CDATA[ ]]>").append("</work_order>");					
					valueXmlString.append("<campgn_no protect = \"0\">").append("<![CDATA[" + campgnNo + "]]>").append("</campgn_no>");					
				}
				else
				{
					valueXmlString.append("<work_order protect = \"0\">").append("<![CDATA[" + workOrder + "]]>").append("</work_order>");					
					valueXmlString.append("<campgn_no protect = \"1\">").append("<![CDATA[ ]]>").append("</campgn_no>");					
				}
								
			}
			else if(currentColumn.trim().equalsIgnoreCase("campaign_no"))
			{
				campgnNo = checkNull(genericUtility.getColumnValue("campgn_no", dom));
				workOrder = checkNull(genericUtility.getColumnValue("work_order", dom));
				if ( campgnNo != null && !"null".equals(campgnNo) && campgnNo.trim().length() > 0  )
				{
					valueXmlString.append("<work_order protect = \"1\">").append("<![CDATA[]]>").append("</work_order>");					
				}
				else
				{
					valueXmlString.append("<work_order protect = \"0\">").append("<![CDATA[" + workOrder + "]]>").append("</work_order>");					
				}
								
			}

			valueXmlString.append("</Detail1>");
			break;

		}	
		valueXmlString.append("</Root>");
		System.out.println(" Itemchanged called for [" + currentColumn + "] valueXmlString [" + valueXmlString.toString() + "]");
	}
	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 d)
		{
			d.printStackTrace();
		}			
	}
	return valueXmlString.toString();
}
	 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 checkNull(String input) 
	{
		if(input == null)
		{
			input = "";
		}
		return input;
	}
	
	private String isExist(String table, String field, String value,Connection conn) throws SQLException
	{
		String sql = "",retStr="";
		PreparedStatement pstmt = null;
		ResultSet rs = null ;
		int cnt=0;

		sql = " SELECT COUNT(1) FROM "+ table + " WHERE " + field + " = ? ";
		pstmt =  conn.prepareStatement(sql);
		pstmt.setString(1,value);
		rs = pstmt.executeQuery();
		if(rs.next())
		{
			cnt = rs.getInt(1);
		}
		rs.close();
		rs = null;
		pstmt.close(); 
		pstmt = null;
		if( cnt > 0)
		{
			retStr = "TRUE";
		}
		if( cnt == 0 )
		{
			retStr = "FALSE";
		}
		System.out.println("@@@@ isexist["+value+"]:::["+retStr+"]:::["+cnt+"]");
		return retStr;
	}

	
	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();
			if(rs.next())
			{
				msgType = rs.getString("MSG_TYPE");
			}
			rs.close();
			rs = null;
			pstmt.close();
			pstmt = null;
		}
		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;
	}



}	
