package ibase.webitm.ejb.mfg;

import java.rmi.RemoteException;
import java.util.*;
import java.util.Date;
//import java.text.*;
import java.sql.*;
import org.w3c.dom.*;
//import javax.xml.parsers.*;
import javax.ejb.*;
import ibase.webitm.utility.ITMException;
//import ibase.webitm.utility.*;
import ibase.system.config.*;
import ibase.webitm.ejb.*;
//import ibase.utility.CommonConstants;
import ibase.webitm.utility.GenericUtility;
import java.text.SimpleDateFormat;
import javax.naming.InitialContext;
import javax.ejb.Stateless; // added for ejb3

@Stateless // added for ejb3

public class RunMRP extends ValidatorEJB implements  RunMRPLocal,RunMRPRemote //SessionBean
{

	GenericUtility genericUtility = GenericUtility.getInstance();
	ITMDBAccessEJB itmDBAccessEJB = new ITMDBAccessEJB();
	Connection conn = null;
	SimpleDateFormat simpleDateFormat = null;

	/*public void ejbCreate() throws RemoteException, CreateException
	{
		System.out.println("Create Method Called...");
	}
	public void ejbRemove()
	{
	}
	public void ejbActivate()
	{
	}
	public void ejbPassivate()
	{
	}*/
	public String wfValData() throws RemoteException,ITMException
	{
		System.out.println("wfValData()...");
		return "";
	}

	// Item Change
	public String itemChanged() throws RemoteException,ITMException
	{
		System.out.println("itemChanged Called...");
		return "";
	}
	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 errString = null;
		GenericUtility genericUtility = GenericUtility.getInstance();
		try
		{
			if (xmlString != null && xmlString.trim().length()!=0)
			{
				dom = genericUtility.parseString(xmlString);
			}
			if (xmlString1 != null && xmlString1.trim().length()!=0)
			{
				dom1 = genericUtility.parseString(xmlString1);
			}
			if (xmlString2 != null && xmlString2.trim().length()!=0)
			{
				dom2 = genericUtility.parseString(xmlString2);
			}
			errString = itemChanged(dom, dom1, dom2, objContext, currentColumn, editFlag, xtraParams);
		}
		catch (Exception e)
		{
			System.out.println ("Exception :ProcessControlEJB :itemChanged(String,String):" + e.getMessage() + ":");
			errString = genericUtility.createErrorString(e);
			throw new ITMException(e);
		}
		System.out.println ("returning from ProcessControlEJB itemChanged");
		return errString;
	}
	public String itemChanged(Document dom, Document dom1, Document dom2, String objContext, String currentColumn, String editFlag, String xtraParams) throws RemoteException,ITMException
	{
		String returnValue="";
		String returnValue1="";
		String returnValue2="";
		String itemCodeDom="";
		String itemCodeDom1="";
		String itemCodeDom2="";
		ResultSet rs = null;
		String sql = "";
		String columnValue = "";
		String userId = "";
		String errString="";
		Connection connectionObject = null;
		Statement stmt = null;
		StringBuffer valueXmlString = new StringBuffer();
		int currentFormNo = 0;
		GenericUtility genericUtility = GenericUtility.getInstance();
		//ITMDBAccessHome itmDBAccessHome = null;
		ITMDBAccessLocal itmDBAccess = null;
		try
		{
			simpleDateFormat = new SimpleDateFormat(genericUtility.getApplDateFormat());
		 	AppConnectParm appConnect = new AppConnectParm();
			Properties p = appConnect.getProperty();
			InitialContext ctx = new InitialContext(p);
			itmDBAccess = (ITMDBAccessLocal)ctx.lookup("ibase/ITMDBAccessEJB/local");
			//itmDBAccess = itmDBAccessHome.create();
			connectionObject = itmDBAccess.getConnection();
			userId = genericUtility.getValueFromXTRA_PARAMS(xtraParams,"loginCode");

			columnValue = genericUtility.getColumnValue(currentColumn,dom);
			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:
					valueXmlString.append("<Detail1>");
					if(currentColumn.trim().equals("itm_default"))
					{
						Calendar cal = Calendar.getInstance();
						Date d = new Date();
						String runDate =  simpleDateFormat.format(d); // 01-10-2007 manoharan
						cal.setTime(d);
						cal.set(Calendar.DATE,1);
						d = cal.getTime();
						String fromDate = simpleDateFormat.format(d);
						cal.setTime(d);
						cal.add(Calendar.MONTH,3);
						cal.set(Calendar.DATE,0);
						d = cal.getTime();
						String toDate = simpleDateFormat.format(d);
						System.out.println("From Date :" + fromDate + " To Date :" + toDate);
						valueXmlString.append("<date_from>").append(fromDate).append("</date_from>");
						valueXmlString.append("<date_to>").append(toDate).append("</date_to>");
						valueXmlString.append("<site_code__from>").append("0").append("</site_code__from>");
						valueXmlString.append("<site_code__to>").append("ZZ").append("</site_code__to>");
						valueXmlString.append("<item_code__from>").append("0").append("</item_code__from>");
						valueXmlString.append("<item_code__to>").append("ZZ").append("</item_code__to>");
						valueXmlString.append("<item_ser__from>").append("0").append("</item_ser__from>");
						valueXmlString.append("<item_ser__to>").append("ZZ").append("</item_ser__to>");
						valueXmlString.append("<process_cycle>").append("0").append("</process_cycle>");
						valueXmlString.append("<run_date>").append(runDate).append("</run_date>"); // 01-10-2007 manoharan

						valueXmlString.append("<dis_plan>").append("Y").append("</dis_plan>");
						valueXmlString.append("<mfg_plan>").append("Y").append("</mfg_plan>");
						valueXmlString.append("<mat_plan>").append("Y").append("</mat_plan>");
						valueXmlString.append("<made_to_stock>").append("0").append("</made_to_stock>");
						valueXmlString.append("<made_to_order>").append("0").append("</made_to_order>");
						valueXmlString.append("<balance_intersite>").append("N").append("</balance_intersite>");
						//valueXmlString.append("<cons_supp>").append("1").append("</cons_supp>");
						valueXmlString.append("<gen_ind>").append("Y").append("</gen_ind>");
					}
					valueXmlString.append("</Detail1>");
					break;
			}
			valueXmlString.append("</Root>");
		}
		catch(Exception e)
		{
			System.out.println("Exception :[RunMRP][itemChanged::case 1:] :==>\n"+e.getMessage());
			e.printStackTrace();
			throw new ITMException(e);
		}
		return valueXmlString.toString();
	}

	// Validation
	public String wfValData(String xmlString, String xmlString1,String xmlString2, String objContext, String editFlag, String xtraParams) throws RemoteException,ITMException
	{
		Document dom = null;
		Document dom1 = null;
		Document dom2 = null;
		String  errString = "";
		System.out.println("wfValData(String)>>>");
		try
		{
			dom = parseString(xmlString);
			System.out.println("RunMRP : wfValData(String xmlString) : ==>\n" + xmlString );
			System.out.println("RunMRP : wfValData(String xmlString1) : ==>\n" + xmlString1 );
			dom1 = parseString(xmlString1);
			if (xmlString2.trim().length() > 0 )
			{
				dom2 = parseString("<Root>" + xmlString2+ "</Root>");
			}
			errString = wfValData(dom,dom1,dom2,objContext,editFlag,xtraParams);
		}
		catch(Exception e)
		{
			System.out.println("Exception : RunMRP : wfValData(String xmlString) : ==>\n"+e.getMessage());
			e.printStackTrace();
			throw new ITMException(e);
		}
		return (errString);
	}

	public String wfValData(Document dom, Document dom1, Document dom2, String objContext, String editFlag, String xtraParams) throws RemoteException, ITMException
	{
		NodeList parentNodeList = null;
		NodeList childNodeList = null;
		Node parentNode = null;
		Node childNode = null;
		String childNodeName = "";
		String  errString = "";
		int ctr,currentFormNo=0;
		int childNodeListLength;
		int count = 0;

		String siteCodeFrom = "";
		String siteCodeTo = "";
		String itemCodeFrom = "";
		String itemCodeTo = "";
		String itemSerFrom = "";
		String itemSerTo = "";
		String errCode = "";
		String userId = "";
		String sql = "";
		String itemcodeTo = "";
		//String itemSerTo = "";
		//String itemSerFrom = "";

		PreparedStatement pstmt = null;
		ResultSet rs = null;
		try
		{
			simpleDateFormat = new SimpleDateFormat(genericUtility.getApplDateFormat());
			conn = getConnection();
			userId = getValueFromXTRA_PARAMS(xtraParams,"userId");
			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();

							int cnt;
						System.out.println("childNodeName 0. : " + childNodeName);
						if (childNodeName.equals("date_to"))
						{
							if (childNode.getFirstChild() == null || genericUtility.getColumnValue("date_from",dom) == null)
							{
								errCode = "VMRPDATE1";
								errString = getErrorString("date_to",errCode,userId);
								break;
							}
							String df = genericUtility.getColumnValue("date_from",dom);
							String dt = genericUtility.getColumnValue("date_to",dom);
							System.out.println("date From -->" + df );
							System.out.println("date To   -->" + dt );
							System.out.println("Parsed " + simpleDateFormat.parse(df));

							java.util.Date fromDate = new Date(simpleDateFormat.parse(genericUtility.getColumnValue("date_from",dom)).getTime());
							java.util.Date toDate = new Date(simpleDateFormat.parse(genericUtility.getColumnValue("date_to",dom)).getTime());
							if(fromDate.after(toDate))
							{
								System.out.println("Error...");
								errCode = "VMRPDATE1";
								errString = getErrorString("date_to",errCode,userId);
								break;
							}
							else
							    System.out.println("No Error...");
						}
						if (childNodeName.equals("site_code__to"))
						{
							if (childNode.getFirstChild() == null || genericUtility.getColumnValue("site_code__from",dom) == null)
							{
								errCode = "VMRPSITE1";
								errString = getErrorString("site_code__to",errCode,userId);
								break;
							}
							siteCodeFrom = genericUtility.getColumnValue("site_code__from",dom);
							siteCodeTo = genericUtility.getColumnValue("site_code__to",dom);

							if(siteCodeTo.compareTo(siteCodeFrom)<0)
							{
								errCode = "VMRPSITE1";
								errString = getErrorString("site_code__to",errCode,userId);
								break;
							}
							count = 0;
						}
						if (childNodeName.equals("item_code__to"))
						{
							if (childNode.getFirstChild() == null || genericUtility.getColumnValue("item_code__from",dom) == null)
							{
								errCode = "VMRPSITE1";
								errString = getErrorString("item_code__to",errCode,userId);
								break;
							}
							itemCodeFrom = genericUtility.getColumnValue("item_code__from",dom);
							itemCodeTo = genericUtility.getColumnValue("item_code__to",dom);
							if(itemCodeTo.compareTo(itemCodeFrom)<0)
							{
								errCode = "VMRPITEMS1";
								errString = getErrorString("item_code__to",errCode,userId);
								break;
							}
							count = 0;
						}
						if (childNodeName.equals("item_ser__to"))
						{
							if (childNode.getFirstChild() == null || genericUtility.getColumnValue("item_ser__from",dom) == null)
							{
								errCode = "VMRPSITE1";
								errString = getErrorString("item_ser__to",errCode,userId);
								break;
							}
							itemSerFrom = genericUtility.getColumnValue("item_ser__from",dom);
							itemSerTo = genericUtility.getColumnValue("item_ser__to",dom);
							if(itemSerTo.compareTo(itemSerFrom)<0)
							{
								errCode = "VMRPITEMS1";
								errString = getErrorString("item_ser__to",errCode,userId);
								break;
							}
							count = 0;
						}
						if (childNodeName.equals("process_cycle"))
						{
							if (childNode.getFirstChild() == null || Integer.parseInt(genericUtility.getColumnValue("process_cycle",dom)) < 0)
							{
								errCode = "VMRPCYCL1";
								errString = getErrorString("process_cycle",errCode,userId);
								break;
							}
						}
						if (childNodeName.equals("gen_ind"))
						{
							if (childNode.getFirstChild() == null || genericUtility.getColumnValue("gen_ind",dom) == null)
							{
								errCode = "VMRPGIND";
								errString = getErrorString("gen_ind",errCode,userId);
								break;
							}
						}
					}
				}
			}
		}
		catch(Exception e)
		{
			System.out.println("Exception ::"+e);
			e.printStackTrace();
			errString = e.getMessage();
			throw new ITMException(e);
		}
		finally
		{
			try
			{
				//System.out.println("Closing Connection.....");
				//conn.close();
				//conn = null;
			}catch(Exception se){}
		}
		return errString;
	}

}
