package ibase.webitm.ejb.fin;


import java.rmi.RemoteException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import ibase.system.config.ConnDriver;
import ibase.webitm.ejb.ValidatorEJB;
import ibase.webitm.utility.GenericUtility;
import ibase.webitm.utility.ITMException;

import javax.ejb.Stateless;

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

@Stateless
public class ContributionProcessIC extends ValidatorEJB implements ContributionProcessICLocal, ContributionProcessICRemote{

	
	public ContributionProcessIC() {
        System.out.println("<-----------Inside Contribution Process-------------->");
    }
	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 = "";

		NodeList parentNodeList = null;
		NodeList childNodeList = null;
		Node parentNode = null;
		Node childNode = null;
		String childNodeName = "";

		try {
		    dom = parseString(xmlString);
		    dom1 = parseString(xmlString1);
		    if (xmlString2.trim().length() > 0) {
			dom2 = parseString("<Root>" + xmlString2 + "</Root>");
		    }
		    if (objContext != null && Integer.parseInt(objContext) == 1) {
			parentNodeList = dom2.getElementsByTagName("Header0");
			parentNode = parentNodeList.item(1);
			childNodeList = parentNode.getChildNodes();
			for (int x = 0; x < childNodeList.getLength(); x++) {
			    childNode = childNodeList.item(x);
			    childNodeName = childNode.getNodeName();
			    if (childNodeName.equalsIgnoreCase("Detail1")) {
				errString = wfValData(dom, dom1, dom2, "1", editFlag, xtraParams);
				if (errString != null && errString.trim().length() > 0)
				    break;
			    } else if (childNodeName.equalsIgnoreCase("Detail2")) {
				errString = wfValData(dom, dom1, dom2, "2", editFlag, xtraParams);
				break;
			    }
			}
		    }

		    else {
			errString = wfValData(dom, dom1, dom2, objContext, editFlag, xtraParams);
		    }
		} catch (Exception e) {
		    System.out.println("Exception : Inside DocumentMaster wfValData Method ..> " + e.getMessage());
		    throw new ITMException(e);
		}
		return (errString);
	    }

	    public String wfValData(Document dom, Document dom1, Document dom2, String objContext, String editFlag, String xtraParams) throws RemoteException, ITMException {
		GenericUtility genericUtility;
		NodeList parentNodeList = null;
		NodeList childNodeList = null;
		Node parentNode = null;
		Node childNode = null;
		int ctr = 0, currentFormNo = 0, childNodeListLength = 0, cnt = 0;
		int count=0, count1=0;
		String childNodeName = null;
		String errString = "";
		String errCode = "";
		Connection conn = null;
		PreparedStatement pStmt = null;
		ResultSet rs = null;
		String sql = "";
		String userId = "";
		

		String finEntity="", siteCodeFr="", siteCodeTo="";
		String finEnt1="", finEnt2="";
		String tranDateFr=null, tranDateTo=null;
		Timestamp startDate=null, endDate=null ;
		
		try {
		    ConnDriver connDriver = new ConnDriver();
		    conn = connDriver.getConnectDB("DriverITM");
		    conn.setAutoCommit(false);
		    connDriver = null;
		    userId = getValueFromXTRA_PARAMS(xtraParams, "loginCode");
		    genericUtility = GenericUtility.getInstance();

		    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("fin_entity")) {
				finEntity = genericUtility.getColumnValue("fin_entity", dom);
//				siteCodeFr = genericUtility.getColumnValue("site_code_from", dom);
//				siteCodeTo = genericUtility.getColumnValue("site_code_to", dom);
				
				finEntity = finEntity == null ? "" : finEntity.trim();
				if (finEntity.length() == 0) {
				    errCode = "VMFINENTNL";
				    errString = getErrorString("fin_entity", errCode, userId);
				    break;
				} else {
				    sql = "select count (1) from finent where fin_entity=?";
				    pStmt = conn.prepareStatement(sql);
				    pStmt.setString(1, finEntity);
				    rs = pStmt.executeQuery();

				    if (rs.next()) {
					cnt = rs.getInt(1);
				    }
				    rs.close();
				    rs = null;
				    pStmt.close();
				    pStmt = null;
				    if (cnt == 0) {
					errCode = "VMFINENTNF";
					errString = getErrorString("fin_entity", errCode, userId);
					break;
				    }
				}
			    }else if (childNodeName.equalsIgnoreCase("site_code_from")) {
					siteCodeFr = genericUtility.getColumnValue("site_code_from", dom);
					siteCodeFr = siteCodeFr == null ? "" : siteCodeFr.trim();
					finEntity = genericUtility.getColumnValue("fin_entity", dom);
					if (siteCodeFr.trim().length() == 0) {
					    errCode = "VMSITFRNL";
					    errString = getErrorString("site_code_from", errCode, userId);
					    break;
					} else {
						if(!(siteCodeFr).equals("00")){
					    sql = "select count(*), fin_entity from site where site_code=? GROUP BY fin_entity";
					    pStmt = conn.prepareStatement(sql);
					    pStmt.setString(1, siteCodeFr);
					    rs = pStmt.executeQuery();

					    if (rs.next()) {
						count = rs.getInt(1);
						finEnt1=rs.getString(2);
					    }
					    rs.close();
					    rs = null;
					    pStmt.close();
					    pStmt = null;
					    
					    System.out.println("count----->"+cnt);
					    if (count == 0) {
						errCode = "VMSITFRNF";
						errString = getErrorString("site_code_from", errCode, userId);
						break;
					    }
					    if(!(finEnt1.trim()).equals(finEntity.trim())){
					    errCode = "VMSIFFEM";
						errString = getErrorString("fin_entity", errCode, userId);
						break;	
					    }
						}
					}
				    }else if (childNodeName.equalsIgnoreCase("site_code_to")) {
						siteCodeTo = genericUtility.getColumnValue("site_code_to", dom);
						siteCodeTo = siteCodeTo == null ? "" : siteCodeTo.trim();
						finEntity = genericUtility.getColumnValue("fin_entity", dom);
						finEntity = finEntity == null ? "" : finEntity.trim();
						if (siteCodeTo.length() == 0) {
						    errCode = "VMSITTONL";
						    errString = getErrorString("site_code_to", errCode, userId);
						    break;
						} else {
							if(!(siteCodeTo).equals("ZZ")){
						    sql = "select count(*), fin_entity from site where site_code=? GROUP BY fin_entity";
						    pStmt = conn.prepareStatement(sql);
						    pStmt.setString(1, siteCodeTo);
						    rs = pStmt.executeQuery();

						    if (rs.next()) {
							count1 = rs.getInt(1);
							finEnt2=rs.getString(2);
						    }
						    rs.close();
						    rs = null;
						    pStmt.close();
						    pStmt = null;
						    if (count1 == 0) {
							errCode = "VMSITTONF";
							errString = getErrorString("site_code_to", errCode, userId);
							break;
						    }
						    System.out.println("fin entity---->"+finEnt2);
						    System.out.println("fin entityeee---->"+finEntity);
						    
						    if(!(finEnt2.trim()).equals(finEntity.trim())){
							    errCode = "VMSITFEM";
								errString = getErrorString("fin_entity", errCode, userId);
								break;	
							    }
							}
						}
					}else if (childNodeName.equalsIgnoreCase("tran_date_from")) {
						tranDateFr = genericUtility.getColumnValue("tran_date_from", dom);
						tranDateFr = tranDateFr == null ? "" : tranDateFr.trim();
						
						if (tranDateFr.length() == 0) {
						    errCode = "VMTRDTFNL";
						    errString = getErrorString("tran_date_from", errCode, userId);
						    break;
						}
					}else if (childNodeName.equalsIgnoreCase("tran_date_to")) {
						tranDateTo = genericUtility.getColumnValue("tran_date_to", dom);
						tranDateTo = tranDateTo == null ? "" : tranDateTo.trim();
						tranDateFr = genericUtility.getColumnValue("tran_date_from", dom);
						tranDateFr = tranDateFr == null ? "" : tranDateFr.trim();
						if (tranDateTo.length() == 0) {
						    errCode = "VMTRDTTNL";
						    errString = getErrorString("tran_date_to", errCode, userId);
						    break;
						}else{
							startDate = Timestamp.valueOf(genericUtility.getValidDateString(tranDateFr, genericUtility.getApplDateFormat(),genericUtility.getDBDateFormat()) + " 00:00:00.0");
							endDate = Timestamp.valueOf(genericUtility.getValidDateString(tranDateTo, genericUtility.getApplDateFormat(),genericUtility.getDBDateFormat()) + " 00:00:00.0");
							if(startDate!=null && endDate!=null && startDate.after(endDate)){
								errCode = "VMINVLDT";
							    errString = getErrorString("tran_date_from", errCode, userId);
							    break;	
							}
							if(startDate!=null && endDate!=null && endDate.before(startDate)){
								errCode = "VMINVLDT1";
							    errString = getErrorString("tran_date_to", errCode, userId);
							    break;	
							}
						}
					}
				}
			break;
		    }
		} catch (Exception e) {
		    e.printStackTrace();
		    errString = e.getMessage();
		    throw new ITMException(e);
		} finally {
		    try {
			if (conn != null) {
			    conn.close();
			}
			conn = null;
		    } catch (Exception d) {
			d.printStackTrace();
		    }
		}
		return errString;
	    }
	    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 = "";
	    	try {
	    	    dom = parseString(xmlString);
	    	    dom1 = parseString(xmlString1);
	    	    if (xmlString2.trim().length() > 0) {
	    		dom2 = parseString(xmlString2);
	    	    }
	    	    valueXmlString = itemChanged(dom, dom1, dom2, objContext, currentColumn, editFlag, xtraParams);
	    	} catch (Exception e) {
	    	    System.out.println("Exception : [itemChanged(String,String)] :==>\n" + e.getMessage());
	    	    throw new ITMException(e);
	    	}
	    	return valueXmlString;
	        }

	        public String itemChanged(Document dom, Document dom1, Document dom2, String objContext, String currentColumn, String editFlag, String xtraParams) throws RemoteException, ITMException {
	    	GenericUtility genericUtility;
	    	StringBuffer valueXmlString = new StringBuffer();
	    	Connection conn = null;
	    	PreparedStatement pStmt = null;
	    	ResultSet rs = null;
	    	String sql = "";
	    	int currentFormNo = 0;
	    	SimpleDateFormat sdf=null;
	    	SimpleDateFormat sdf1=null;
	    	Calendar cal = Calendar.getInstance();
	    	Calendar cal1=Calendar.getInstance();
			java.sql.Timestamp currDate = new java.sql.Timestamp( System.currentTimeMillis() ); 
			String firstDate="";
			String lastDate="";
			
			String modFirstDate="";
			String modLastDate="";
			
			String tranDateFr="", tranDateTo="";
	    	
	    	try {
	    	    genericUtility = GenericUtility.getInstance();
	    	    ConnDriver conndriver = new ConnDriver();
	    	    conn = conndriver.getConnectDB("DriverITM");
	    	    conn.setAutoCommit(false);
	    	    conndriver = null;
	    	    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().equalsIgnoreCase("itm_default")){
	    			sdf=new SimpleDateFormat(getApplDateFormat());
	    			
	    			
	    			 cal.setTime(currDate); //------> Last Date of the Month 
	    			 cal.set(Calendar.DAY_OF_MONTH, cal.getActualMaximum(Calendar.DAY_OF_MONTH));  
	    			 lastDate=sdf.format(cal.getTime());
	    			
	    			
	    			cal.set(Calendar.DAY_OF_MONTH, cal.getActualMinimum(Calendar.DAY_OF_MONTH)); 
	    			System.out.println(sdf.format(cal.getTime()));
	    			firstDate=sdf.format(cal.getTime());
	    			
	    			valueXmlString.append("<site_code_from>").append("00").append("</site_code_from>\r\n");
	    			valueXmlString.append("<site_code_to>").append("ZZ").append("</site_code_to>\r\n");
	    			valueXmlString.append("<tran_date_from>").append(firstDate).append("</tran_date_from>\r\n");
	    			valueXmlString.append("<tran_date_to>").append(lastDate).append("</tran_date_to>\r\n");
	    		}
	    		
	    		else if(currentColumn.equalsIgnoreCase("tran_date_from")){
	    			sdf1=new SimpleDateFormat(getApplDateFormat());
	    			tranDateFr=genericUtility.getColumnValue("tran_date_from", dom);
	    			tranDateFr=genericUtility.getValidDateString(tranDateFr, genericUtility.getApplDateFormat(), genericUtility.getDBDateFormat());
	    			Timestamp tranDateFrom=java.sql.Timestamp.valueOf(tranDateFr + " 00:00:00");
	    			if(tranDateFrom!=null){
	    				cal1.setTime(tranDateFrom);
	    				cal1.set(Calendar.DAY_OF_MONTH, cal.getActualMinimum(Calendar.DAY_OF_MONTH));  
		    			lastDate=sdf1.format(cal.getTime());
		    			System.out.println(sdf1.format(cal1.getTime()));
		    			modFirstDate=sdf1.format(cal1.getTime());
	    			}
	    			valueXmlString.append("<tran_date_from>").append(modFirstDate).append("</tran_date_from>\r\n");
	    		}
	    		
	    		else if(currentColumn.equalsIgnoreCase("tran_date_to")){
	    			sdf1=new SimpleDateFormat(getApplDateFormat());
	    			tranDateTo=genericUtility.getColumnValue("tran_date_to", dom);
	    			tranDateTo=genericUtility.getValidDateString(tranDateTo, genericUtility.getApplDateFormat(), genericUtility.getDBDateFormat());
	    			Timestamp tranDtTo=java.sql.Timestamp.valueOf(tranDateTo + " 00:00:00");
	    			
	    			if(tranDtTo!=null){
	    				cal1.setTime(tranDtTo);
	    				cal1.set(Calendar.DAY_OF_MONTH, cal1.getActualMaximum(Calendar.DAY_OF_MONTH));  
		    			lastDate=sdf1.format(cal1.getTime());
		    			modLastDate=sdf1.format(cal1.getTime());
	    			}
	    			valueXmlString.append("<tran_date_to>").append(modLastDate).append("</tran_date_to>\r\n");
	    		}
	    		valueXmlString.append("</Detail1 >");
	    		break;
	    	    }
	    	    valueXmlString.append("</Root>");
	    	} catch (Exception e) {
	    	    e.printStackTrace();
	    	    throw new ITMException(e);
	    	} finally {
	    	    try {
	    		if (conn != null) {
	    		    conn.close();
	    		    conn = null;
	    		}
	    	    } catch (Exception e1) {
	    		e1.printStackTrace();
	    	    }
	    	}
	    	return valueXmlString.toString();
	        }

}
