package ibase.webitm.ejb.dis;

import ibase.system.config.AppConnectParm;
import ibase.system.config.ConnDriver;
import ibase.utility.UserInfoBean;
import ibase.webitm.ejb.DBAccessLocal;
import ibase.webitm.ejb.ITMDBAccessEJB;
import ibase.webitm.ejb.MasterStatefulLocal;
import ibase.webitm.ejb.ProcessEJB;
import ibase.webitm.ejb.ValidatorEJB;
import ibase.webitm.ejb.fin.FinCommon;
import ibase.webitm.utility.GenericUtility;
import ibase.webitm.utility.ITMException;

import java.rmi.RemoteException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Iterator;
import java.util.StringTokenizer;

import ibase.webitm.ejb.ValidatorEJB;

import javax.ejb.Stateless;
import javax.naming.InitialContext;
import javax.xml.rpc.ParameterMode;

import org.apache.axis.client.Call;
import org.apache.axis.client.Service;
import org.apache.axis.encoding.XMLType;
import org.apache.poi.hssf.record.PageBreakRecord.Break;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

@Stateless
public class PODProcess extends ProcessEJB implements PODProcessLocal,PODProcessRemote
{	 
	  ArrayList<String> podRemainInvIDList=new ArrayList<String>(); 
	 
	   
	 public String process(String xmlString, String xmlString2, String windowName, String xtraParams) throws RemoteException,ITMException
	{
			
			System.out.println("enter in process()");
			String retStr = "";
			Document detailDom = null;
			Document headerDom = null;
			
			GenericUtility genericUtility = GenericUtility.getInstance();			
			try
			{	
				if(xmlString != null && xmlString.trim().length()!=0)
				{
					headerDom = genericUtility.parseString(xmlString); 
					System.out.println("xmlString--->>" + xmlString);
				}
				if(xmlString2 != null && xmlString2.trim().length()!=0)
				{
					detailDom = genericUtility.parseString(xmlString2); 
					System.out.println("xmlString2 --->>" + xmlString2);
				}

				retStr = process(headerDom, detailDom, windowName, xtraParams);

			}
			catch (Exception e)
			{
				System.out.println("Exception :PODProcess :process(String xmlString, String xmlString2, String windowName, String xtraParams):" + e.getMessage() + ":");
				e.printStackTrace();
				retStr = e.getMessage();
			}
			return retStr;

		}
	  
	  
public String process() throws RemoteException,ITMException
{
		  return "";
}

public String process(Document dom, Document dom2, String windowName, String xtraParams) throws RemoteException,ITMException
{
		System.out.println("enter in process(dom) ");
		ArrayList <String>inv45dayList=new ArrayList<String>();
		ArrayList<String> podProcessInvIDList=new ArrayList<String>(); 
		ArrayList<String> podNotConfList=new ArrayList<String>();
		Connection conn = null;
		ConnDriver connDriver = null;
		GenericUtility genericUtility = null;
		ProofOfDelivery podObject=null;
		ITMDBAccessEJB itmDBAccessEJB = null;
		ValidatorEJB vdt=null;
		PreparedStatement pstmt=null;
		ResultSet rs=null;
		int cnt=0;
		String siteCode="",custCodeFrm="",custCodeTo="",invType="",errorString="",errCode="",userId="";
		String sql="",invoiceId="",priceList="";
		try{
			genericUtility = GenericUtility.getInstance();
			itmDBAccessEJB = new ITMDBAccessEJB();
			podObject=ProofOfDelivery.getInstance();
		    vdt=new ValidatorEJB();
			connDriver = new ConnDriver();
			conn = connDriver.getConnectDB("DriverITM");
			connDriver = null;
			userId = vdt.getValueFromXTRA_PARAMS(xtraParams,"loginCode");
		siteCode=genericUtility.getColumnValue("site_code", dom);
		custCodeFrm=genericUtility.getColumnValue("cust_code_from", dom);
		custCodeTo=genericUtility.getColumnValue("cust_code_to", dom);
		invType=genericUtility.getColumnValue("inv_type", dom);
		
		siteCode=siteCode==null ? "" :siteCode.trim();
		custCodeFrm=custCodeFrm==null ? "" :custCodeFrm.trim();
		custCodeTo=custCodeTo==null ? "" :custCodeTo.trim();
		invType=invType==null ? "" :invType.trim();
		System.out.println("SiteCode-133-->>["+siteCode+"]");
		System.out.println("custCodeFrm--->>["+custCodeFrm+"]");
		System.out.println("custCodeTo--->>["+custCodeTo+"]");
		System.out.println("invType--->>["+invType+"]");
		
		//Validation for Site code
		if (siteCode.length() == 0 )
		{							
				errCode = "VTSITECNE";
				errorString = vdt.getErrorString("site_code",errCode,userId);
				return errorString;				
		
		}else
		{							
			cnt=podObject.getDBRowCount(conn,"site","site_code",siteCode);
			if(cnt == 0)
			{
				System.out.println("site_code not exist validation fire");
				errCode = "VTSITENEX";
				errorString = vdt.getErrorString("site_code",errCode,userId);	
				return errorString;
			}
		
		  }
		//Validation for Customer Code From
		if (custCodeFrm.length() == 0 )
		{							
				errCode = "VTCUSTCNE";
				errorString = vdt.getErrorString("cust_code_from",errCode,userId);
				return errorString;
		
		}else
		{							
			cnt=podObject.getDBRowCount(conn,"customer","cust_code",custCodeFrm);
			if(cnt == 0)
			{
				System.out.println("custCodeFrom not exist validation fire");
				errCode = "VTCUSTNEX";
				errorString = vdt.getErrorString("cust_code_from",errCode,userId);	
				return errorString;
			}
		
		}
		
		//Validation for Customer Code To 
		if (custCodeTo.length() == 0 )
		{							
				errCode = "VTCUSTCNE";
				errorString = vdt.getErrorString("cust_code_to",errCode,userId);
				return errorString;
		
		}else
		{							
			cnt=podObject.getDBRowCount(conn,"customer","cust_code",custCodeTo);
			if(cnt == 0)
			{
				System.out.println("custCodeTo not exist validation fire");
				errCode = "VTCUSTNEX";
				errorString = vdt.getErrorString("cust_code_to",errCode,userId);	
				return errorString;
			}
		
		}
		//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
		if(custCodeFrm.length() > 0 && custCodeTo.length() > 0 && siteCode.length() > 0){			
		sql="select invoice_id from invoice where cust_code__bil between ? and  ? and site_code = ? "
				+ "and sysdate - conf_date > 517";
		pstmt=conn.prepareStatement(sql);
		pstmt.setString(1, custCodeFrm);
		pstmt.setString(2, custCodeTo);
		pstmt.setString(3, siteCode);
		
		rs=pstmt.executeQuery();
		while(rs.next())
		{			
			invoiceId=rs.getString(1);
			invoiceId=invoiceId==null ? "" :invoiceId.trim();			
			inv45dayList.add(invoiceId);			
			
		}
	    rs.close();
	    rs=null;
	    pstmt.close();
	    pstmt=null;
	    priceList=podObject.getNameOrDescrForCode(conn, "site", "price_list", "site_code", siteCode);
		System.out.println("Size of arrayList inv45dayList----->>["+inv45dayList.size()+"]");
		podProcessInvIDList=getPendingInvoiceID( conn, inv45dayList);	
		
		if(podProcessInvIDList.contains("Error"))
		{
			//handle error if array list contain error. 
		}			
		System.out.println("podProcessInvIDList---->>["+podProcessInvIDList+"]");
		System.out.println("Size of podProcessInvIDList---->>["+podProcessInvIDList.size()+"]");
		podNotConfList=getNotConfirmedInvIdFromHdr(conn);
		if(podNotConfList.contains("Error"))
		{
			//handle error if array list contain error. 
		}
		System.out.println("podNotConfList---->>["+podNotConfList+"]");
		System.out.println("Size of podNotConfList---->>["+podNotConfList.size()+"]");
		//check in podNotConfList if invoice id  in podProcessInvIDList present or not.
		//if present then remove from podProcessInvIDList.
		if(podNotConfList.size() > 0 && podProcessInvIDList.size() > 0)
		{
			for(String id : podNotConfList)
			{
				if(podProcessInvIDList.contains(id))
				{
					System.out.println("id removed------>>["+id+"]");
					podProcessInvIDList.remove(id);
				}
			}
		}
		
		System.out.println("Final invoice Id ready for debit note---->>["+podProcessInvIDList+"]");	
		
		
		
		
		
		
		
		
		}
		}//end try
		catch(Exception e)
		{
			System.out.println("Exception in PODProcess Class---------");
			e.printStackTrace();
		}
		
		finally{
			try{
			if(conn !=null)
			{
				conn.close();
			}
			}
			catch(Exception e)
			{
				e.printStackTrace();
			}
		}
		return errorString;

}
// Return array list whoes invoice id not confirmed in spl_sales_por_hdr table.
private ArrayList<String> getNotConfirmedInvIdFromHdr(Connection conn)
{
	ArrayList<String> podNotConfListL=new ArrayList<String>();
	PreparedStatement pstmt=null;
	ResultSet rs=null;
	String sql="",invID="";
	try
	{
		sql="select invoice_id from spl_sales_por_hdr where confirmed = ? ";
		pstmt=conn.prepareStatement(sql);		
		pstmt.setString(1, "N");
		rs=pstmt.executeQuery();		
		while(rs.next())
		{	
			invID=rs.getString(1);
			invID=invID==null ? "" :invID.trim();
			podNotConfListL.add(invID);				
		}
		System.out.println("Invoice id Not confirmed in HDR table--->>[["+podNotConfListL+"]]");
		rs.close();
		rs=null;
		pstmt.close();
		pstmt=null;
	}
	catch(Exception e)
	{
		System.out.println("-----Exception in getNotConfirmedInvIdFromHdr method-----");
		podNotConfListL.add("Error");
		e.printStackTrace();
	}
	
	return podNotConfListL;
	
}

private ArrayList<String> getPendingInvoiceID(Connection conn,ArrayList<String> invIdList)
{
	System.out.println("--------------checkPODDoneOrNot method------------------");
	System.out.println("ArrayList invIdList--->>[["+invIdList+"]]");
	ArrayList<String> podDoneInvIDList=new ArrayList<String>();
	ArrayList<String> podProcessInvIDListL=new ArrayList<String>();	
	
	String sql="",invoiceIdL="",tranIdL="";
	PreparedStatement pstmt=null,pstmt1=null;
	ResultSet rs=null,rs1=null;
	
	try{		
		//Get all records whoes POD is already generated. 
		sql="select tran_id,invoice_id from spl_sales_por_hdr where confirmed = ? ";
		pstmt=conn.prepareStatement(sql);		
		pstmt.setString(1, "Y");
		rs=pstmt.executeQuery();		
		while(rs.next())
		{	
			tranIdL=rs.getString(1);
			invoiceIdL=rs.getString(2);
			invoiceIdL=invoiceIdL==null ? "" :invoiceIdL.trim();
			tranIdL=tranIdL==null ? "" :tranIdL.trim();
			podDoneInvIDList.add(invoiceIdL);		
			
		}		
		System.out.println("ArrayList podDoneInvIDList--->>[["+podDoneInvIDList+"]]");
		System.out.println("ArrayList podDoneInvIDList size--->>[["+podDoneInvIDList.size()+"]]");
		rs.close();
		rs=null;
		pstmt.close();
		pstmt=null;
		if(invIdList.size() > 0 && podDoneInvIDList.size() > 0){
			System.out.println("---both arraylist contains elements-----------");
			for (String invId : invIdList) {
				
				if(!(podDoneInvIDList.contains(invId))){					
					podProcessInvIDListL.add(invId);
					
				}
				
			}
			
		}
		
		System.out.println("podProcessInvIDList----->>[["+podProcessInvIDListL+"]");
		System.out.println("podProcessInvIDList----->>[["+podProcessInvIDListL.size()+"]");
	}
	catch(Exception e)
	{
		System.out.println("---------Exception in checkPODDoneOrNot method------------------");
		podProcessInvIDListL.add("Error");
		e.printStackTrace();		
		
	}
	finally{
		try{
			if(rs!=null)
			{
				rs.close();rs=null;
			}
			if(pstmt!=null)
			{
				pstmt.close();
				pstmt=null;
			}
			
			
		}
		catch(Exception e)
		{
			System.out.println("Exception in finally checkPODDoneOrNot method-------");
			e.printStackTrace();
		}
	}
	return podProcessInvIDListL;
	
}


}
