package ibase.webitm.ejb.dis;

import ibase.scheduler.utility.interfaces.Schedule;
import ibase.system.config.AppConnectParm;
import ibase.system.config.ConnDriver;
import ibase.webitm.ejb.MasterStatefulLocal;
import ibase.webitm.utility.GenericUtility;
import ibase.webitm.utility.ITMException;

import java.rmi.RemoteException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.Date;
import java.sql.*;
import java.io.*;

import javax.naming.InitialContext;

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

public class GenerateASNSchedular implements Schedule  {

	@Override
	public String schedule(HashMap arg0) throws Exception {
		// TODO Auto-generated method stub
		return null;
	}
	
	@Override
	public String schedulePriority(String arg0) throws Exception {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public String schedule(String scheduleParamXML) throws Exception {
		// TODO Auto-generated method stub
		
		System.out.println("scheduleParamXML ::::"+scheduleParamXML);
		ibase.utility.UserInfoBean userInfo = null;
		String disparmLoginSiteCode = "";
		ConnDriver connDriver = new ConnDriver();
		Connection conn = null;
		Connection connRtm = null;
		conn = connDriver.getConnectDB("DriverITM");
		connRtm = connDriver.getConnectDB("DriverRTM");
		connDriver = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		String queryString = "";
		String sql = "",suppCode="",retString="",tranId="",siteCode="";
		int childNodeListLength = 0;
		String childNodeName = null;

		ArrayList<String> tranIdList = new ArrayList<String>();
		ArrayList<String> asnFailedList = new ArrayList<String>();
		try
		{
			
			/*-----------------to get site code--------------------------------------*/
					
			Document dom = null;
			
			Node currDetail = null ;
			int noOfParam=0;
			GenericUtility genericUtility =GenericUtility.getInstance();
			dom=genericUtility.parseString(scheduleParamXML);
			NodeList paramList = dom.getElementsByTagName( "SCHEDULE" );
            noOfParam = paramList.getLength();            
            NodeList parentNodeList = null,childNodeList = null;
			Node parentNode = null,childNode = null;
		
	
			parentNodeList = dom.getElementsByTagName("USERINFOXML");
            parentNode = parentNodeList.item(0);
			childNodeList = parentNode.getChildNodes();
			childNodeListLength = childNodeList.getLength();
			System.out.println("childNodeListLength  !!!!!"+childNodeListLength);
			for(int ctr = 0; ctr < childNodeListLength; ctr++)
			{
				childNode = childNodeList.item(ctr);
				childNodeName = childNode.getNodeName();
				
				siteCode=genericUtility.getColumnValue("siteCode", dom);
				System.out.println("siteCode  @@@@@@ "+siteCode);
			}
			
			
			/*-------------------------------------------------*/
			
			
			siteCode="SP110";
			
			pstmt = connRtm.prepareStatement("select tran_id from tnt_tran_info where asn_required='Y' and asn_created='N' and SITE_CODE__ASN=?");
			pstmt.setString(1, siteCode);
			rs = pstmt.executeQuery();
			while (rs.next()) 
			{
				tranIdList.add(rs.getString("tran_id"));

			}
			rs.close();
			rs = null;
			pstmt.close();
			pstmt = null;
			System.out.println("tran id list size :::: "+tranIdList.size());
			
			for (int i = 0; i < tranIdList.size(); i++) 
			{
				tranId = tranIdList.get(i);
				System.out.println("tranId :"+tranId);
				retString =  getTrackInfo(tranId);
				System.out.println("retString  is @@@@@@@@ : "+retString);
				if(retString.equalsIgnoreCase("Success"))
				{
					
					try
					{
						System.out.println("execute update query starts!!!!!!!!!");
						sql="update tnt_tran_info set asn_created='Y' where tran_id =?";
						pstmt = connRtm.prepareStatement(sql);
						pstmt.setString(1, tranId);
						pstmt.executeUpdate();
						connRtm.commit();
						System.out.println("Tracking Id : "+tranId+" updated TRACE_STATUS 'Y' succefully!!!");
						
						
					}
					catch(Exception e)
					{
						connRtm.rollback();
						e.printStackTrace();
						System.out.println("Exception :"+e.getMessage());
					}
					finally
					{
						try
						{
							if(pstmt != null)
							{
								pstmt.close();
							}
							if(connRtm != null)
							{
								connRtm.close();
							}
							
						}
						catch(Exception e)
						{
							e.printStackTrace();
						}
						
						
					}
					
				}
				else
				{
					
					asnFailedList.add(tranId);
					System.out.println("Failed despatch id transction : "+asnFailedList);
					
				}
				
				
			}
			
			
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
		
		return null;
	}

	
	
	public String getTrackInfo(String tranId) throws Exception
	{
		ConnDriver connDriver = new ConnDriver();
		Connection conn = null;
		Connection connRtm = null;
		GenericUtility genericUtility = null;
		conn = connDriver.getConnectDB("DriverITM");
		connRtm = connDriver.getConnectDB("DriverRTM");
		PreparedStatement pstmt = null,pstmt1=null,pstmt2=null;
		ResultSet rs = null,rs1=null;
		String scacCode="",purchase_order="",truckNo="",bolNo="",grossWt="",invoiceNo="",pro_no="",seal_no="",tranCode="",confirmed="",shipmentDate="";
		String itemCode="",quantity="",expDt="",packSize="",sscc_14="",lot_no="",sql="",xmlString="",siteCode="",retString="",suppCode="",siteCodeAsn="";
		String invoiceId="",lotNo="",sscc18="",refId="",custProd="",lineNoStr="";
		Date expDate=null;
		Date refDate=null;
		StringBuffer xmlBuff = null;
		Date currentDate = new Date();
		SimpleDateFormat sdf;
		int cnt = 0;
		HashMap tempMapHdr = null;
		HashMap<String, String> tempMap = new HashMap<String, String>();
		int lineNo = 0;
		try
		{
			
			System.out.println("gettrackInfo starts !!! ");
			genericUtility = GenericUtility.getInstance();
		   	sdf = new SimpleDateFormat(genericUtility.getApplDateFormat());
			System.out.println("tranId :"+tranId);
			sql="select SITE_CODE,SHIPMENT_DATE,GROSS_WEIGHT,TRAN_CODE,BOL_NO ,SCAC,SUPP_CODE__ASN,SITE_CODE__ASN  from tnt_tran_info where tran_id=? ";
			
		
			pstmt = connRtm.prepareStatement(sql);
			pstmt.setString(1, tranId);
			rs = pstmt.executeQuery();
			if(rs.next())
			{
					siteCode=rs.getString("SITE_CODE");
					siteCodeAsn=rs.getString("SITE_CODE__ASN");
					shipmentDate=rs.getString("SHIPMENT_DATE");
					grossWt=rs.getString("GROSS_WEIGHT");
					tranCode=rs.getString("TRAN_CODE");
					bolNo=rs.getString("BOL_NO");
					scacCode=rs.getString("SCAC");
					suppCode=rs.getString("SUPP_CODE__ASN");
					
			}
			rs.close();
			rs = null;
			pstmt.close();
			pstmt = null;
			System.out.println("@siteCode "+siteCode+"@ siteCodeAsn "+siteCodeAsn+"@grossWt :"+grossWt);
			System.out.println("@tranCode "+tranCode+"@ bolNo "+bolNo+"@suppCode :"+suppCode+" @scacCode "+scacCode);
			
			
			
			 /*   sql="select INVOICE_ID,ITEM_CODE,LOT_NO,QUANTITY,SSCC_18,EXP_DATE,REF_ID,ref_date,cust_pord  from tnt_tran_infodet where tran_id=? ";
			
			
				pstmt = connRtm.prepareStatement(sql);
				pstmt.setString(1, tranId);
				rs = pstmt.executeQuery();
				if(rs.next())
				{
						invoiceId=rs.getString("INVOICE_ID");
						itemCode=rs.getString("ITEM_CODE");
						lotNo=rs.getString("LOT_NO");
						quantity=rs.getString("QUANTITY");
						sscc18=rs.getString("SSCC_18");
						expDate=rs.getDate("EXP_DATE");
						refId=rs.getString("REF_ID");
						refDate=rs.getDate("REF_DATE");
						custProd=rs.getString("cust_pord");
				}
				rs.close();
				rs = null;
				pstmt.close();
				pstmt = null;
			    System.out.println("@invoiceId :"+invoiceId+"@ itemCode :"+" @lotNo "+lotNo);
			    System.out.println("@quantity :"+quantity+"@ sscc18 :"+sscc18+" @refId "+refId +"@refDate :"+refDate+"@ expDate "+expDate);*/
			
			
			sql="select INVOICE_ID,ITEM_CODE,LOT_NO,QUANTITY,SSCC_18,EXP_DATE,REF_ID,ref_date,cust_pord  from tnt_tran_infodet where tran_id=? ";
			
			
			pstmt = connRtm.prepareStatement(sql);
			pstmt.setString(1, tranId);
			rs = pstmt.executeQuery();
			while(rs.next())
			{
				    cnt++;
					invoiceId=rs.getString("INVOICE_ID");
					itemCode=rs.getString("ITEM_CODE");
					lotNo=rs.getString("LOT_NO");
					quantity=rs.getString("QUANTITY");
					sscc18=rs.getString("SSCC_18");
					expDate=rs.getDate("EXP_DATE");
					refId=rs.getString("REF_ID");
					refDate=rs.getDate("REF_DATE");
					custProd=rs.getString("cust_pord");
					
					invoiceId = invoiceId == null ? "" : invoiceId.trim();
	                itemCode = itemCode == null ? "" : itemCode.trim();
	                lotNo = lotNo == null ? "" : lotNo.trim();
	                quantity = quantity == null ? "" : quantity.trim();
	                sscc18 = sscc18 == null ? "" : sscc18.trim();
	                refId = refId == null ? "" : refId.trim();
	                custProd = custProd == null ? "" : custProd.trim();
	               
	                System.out.println("generateAsnSchedule :invoiceId @@"+ cnt + " " + invoiceId);
	                System.out.println("generateAsnSchedule :itemCode @@"+ cnt + " " + itemCode);
	                System.out.println("generateAsnSchedule :lotNo @@"+ cnt + " " + lotNo);
	                System.out.println("generateAsnSchedule :sscc18 @@"+ cnt + " " + sscc18);
	                System.out.println("generateAsnSchedule :refId @@"+ cnt + " " + refId);
	                System.out.println("generateAsnSchedule :custProd @@"+ cnt + " " + custProd);
	                System.out.println("generateAsnSchedule :expDate @@"+ cnt + " " + expDate);
	                
	                
	                tempMap.put("invoice_id" + cnt, invoiceId);
					tempMap.put("item_code" + cnt, itemCode);
					tempMap.put("lotNo" + cnt, lotNo);
					tempMap.put("quantity" + cnt, quantity);
					tempMap.put("sscc18" + cnt, sscc18);
					tempMap.put("item_code" + cnt, itemCode);
					tempMap.put("refId" + cnt, refId);
					tempMap.put("refDate" + cnt,String.valueOf(refDate));
					tempMap.put("custProd" + cnt, custProd);
					tempMap.put("expDate" + cnt,String.valueOf(expDate));
					
			}
			rs.close();
			rs = null;
			pstmt.close();
			pstmt = null;
		    System.out.println("@invoiceId :"+invoiceId+"@ itemCode :"+" @lotNo "+lotNo);
		    System.out.println("@quantity :"+quantity+"@ sscc18 :"+sscc18+" @refId "+refId +"@refDate :"+refDate+"@ expDate "+expDate);
			    
			System.out.println("map is : "+tempMap);
			
				siteCode = siteCode == null ? "" : siteCode.trim();
				siteCodeAsn = siteCodeAsn == null ? "" : siteCodeAsn.trim();
                shipmentDate = shipmentDate == null ? "" : shipmentDate.trim();
                grossWt = grossWt == null ? "" : grossWt.trim();
                tranCode = tranCode == null ? "" : tranCode.trim();
                bolNo = bolNo == null ? "" : bolNo.trim();
                invoiceId = invoiceId == null ? "" : invoiceId.trim();
                itemCode = itemCode == null ? "" : itemCode.trim();
                lotNo = lotNo == null ? "" : lotNo.trim();
                quantity = quantity == null ? "" : quantity.trim();
                sscc18 = sscc18 == null ? "" : sscc18.trim();
                scacCode = scacCode == null ? "" : scacCode.trim();
                refId = refId == null ? "" : refId.trim();
                suppCode = suppCode == null ? "" : suppCode.trim();
                custProd = custProd == null ? "" : custProd.trim();
			
                xmlBuff = new StringBuffer();
				System.out.println("--XML CREATION !!!!!--");
				xmlBuff.append("<?xml version='1.0' encoding='ISO-8859-1'?>\n");
				xmlBuff.append("<DocumentRoot>");
				xmlBuff.append("<description>").append("Datawindow Root").append("</description>");
				xmlBuff.append("<group0>");
				xmlBuff.append("<description>").append("Group0 description").append("</description>");
				xmlBuff.append("<Header0>");
				xmlBuff.append("<objName><![CDATA[").append("asn").append("]]></objName>");  
				xmlBuff.append("<pageContext><![CDATA[").append("1").append("]]></pageContext>");
				xmlBuff.append("<objContext><![CDATA[").append("1").append("]]></objContext>");
				xmlBuff.append("<editFlag><![CDATA[").append("A").append("]]></editFlag>");
				xmlBuff.append("<focusedColumn><![CDATA[").append("").append("]]></focusedColumn>");
				xmlBuff.append("<action><![CDATA[").append("SAVE").append("]]></action>");
				xmlBuff.append("<elementName><![CDATA[").append("").append("]]></elementName>");
				xmlBuff.append("<keyValue><![CDATA[").append("1").append("]]></keyValue>");
				xmlBuff.append("<taxKeyValue><![CDATA[").append("").append("]]></taxKeyValue>");
				xmlBuff.append("<saveLevel><![CDATA[").append("1").append("]]></saveLevel>");
				xmlBuff.append("<forcedSave><![CDATA[").append(true).append("]]></forcedSave>");
				xmlBuff.append("<taxInFocus><![CDATA[").append(false).append("]]></taxInFocus>");
				xmlBuff.append("<description>").append("Header0 members").append("</description>");	
				/*---details 1 starts----*/
				xmlBuff.append("<Detail1 dbID=\"\" domID=\"1\" objName=\"asn\" objContext=\"1\">");  
				xmlBuff.append("<attribute selected=\"N\" updateFlag=\"A\" status=\"N\" pkNames=\"\"/>");
				xmlBuff.append("<tran_id/>");
				xmlBuff.append("<tran_date><![CDATA["+ sdf.format(currentDate).toString() +"]]></tran_date>");
				xmlBuff.append(	"<asn_no><![CDATA["+refId+"]]></asn_no>");
				xmlBuff.append("<asn_date><![CDATA["+sdf.format(refDate).toString()+"]]></asn_date>");//refId is despatch id of transction
				xmlBuff.append("<tran_code><![CDATA["+ tranCode.trim() +"]]></tran_code>");
				xmlBuff.append("<lr_no><![CDATA["+ bolNo.trim() +"]]></lr_no>");
				xmlBuff.append("<gross_weight><![CDATA["+ grossWt.trim() +"]]></gross_weight>");
				xmlBuff.append("<bol_no><![CDATA["+ bolNo.trim() +"]]></bol_no>");
				//lrDate added by mahendra dated 05-05-2014
				xmlBuff.append("<invoice_no><![CDATA["+ invoiceNo.trim() +"]]></invoice_no>");
				xmlBuff.append("<purc_order><![CDATA["+custProd.trim()+"]]></purc_order>");
				xmlBuff.append("<confirmed><![CDATA["+ confirmed.trim() +"]]></confirmed>");
				xmlBuff.append("<conf_date><![CDATA[]]></conf_date>");
				xmlBuff.append("<emp_code__aprv><![CDATA[]]></emp_code__aprv>");
				xmlBuff.append("<site_code><![CDATA["+  siteCodeAsn.trim() +"]]></site_code>");
				xmlBuff.append("<supp_code><![CDATA["+suppCode.trim()+"]]></supp_code>");	
				xmlBuff.append("<pro_no><![CDATA[]]></pro_no>");
				xmlBuff.append("<scac_code><![CDATA["+ scacCode.trim() +"]]></scac_code>");
				xmlBuff.append("<seal_no><![CDATA[]]></seal_no>");
				xmlBuff.append("</Detail1>");
				/*---details 2 starts----*/
				
				
                System.out.println("cnt is :"+cnt);
				for (int itemCtr = 1; itemCtr <= cnt; itemCtr++)
				{
					lineNo++;
					System.out.println("lineNo is " + lineNo);
				
					/*
					 * start of Details 2
					 */
					System.out.println("start of details 2");
					
					
					xmlBuff.append("<Detail2 dbID='' domID=\"1\" objName=\"asn\" objContext=\"2\">"); 
					xmlBuff.append("<attribute pkNames=\"\" selected=\"N\" updateFlag=\"A\" status=\"N\" />");
					xmlBuff.append("<tran_id/>");
					lineNoStr = "   " + lineNo;
					lineNoStr = lineNoStr.substring(lineNoStr.length() - 3);
					System.out.println("lineNoStr " + lineNoStr);
					xmlBuff.append("<line_no>" + lineNoStr + "</line_no>");
					xmlBuff.append("<item_code><![CDATA["+(String) tempMap.get("item_code" + itemCtr)+"]]></item_code>");					
					xmlBuff.append("<quantity><![CDATA["+ (String) tempMap.get("quantity" + itemCtr) +"]]></quantity>");
					System.out.println("expDate ##@@@@@@@ "+(String) tempMap.get("expDate" + itemCtr));
					
					/*if(!(tempMap.get("expDate" + itemCtr).equalsIgnoreCase("null")))
					{
						System.out.println("expDate : "+tempMap.get("expDate" + itemCtr).trim());
						xmlBuff.append("<exp_date><![CDATA["+(String) tempMap.get("expDate" + itemCtr)+"]]></exp_date>");	
					}*/
					
					xmlBuff.append("<exp_date><![CDATA["+(String) tempMap.get("expDate" + itemCtr)+"]]></exp_date>");						
					xmlBuff.append("<pack_size><![CDATA[]]></pack_size>");					
					xmlBuff.append("<lot_no><![CDATA["+ (String) tempMap.get("lotNo" + itemCtr)  +"]]></lot_no>");					
					xmlBuff.append("<sscc_14><![CDATA["+ (String) tempMap.get("sscc18" + itemCtr) +"]]></sscc_14>");					
					xmlBuff.append("<line_no__ord><![CDATA[]]></line_no__ord>");					
					xmlBuff.append("<no_pallet><![CDATA[]]></no_pallet>");
					
					xmlBuff.append("</Detail2>");
					
				}
				
				xmlBuff.append("</Header0>");
				xmlBuff.append("</group0>");
				xmlBuff.append("</DocumentRoot>");
				xmlString = xmlBuff.toString();
                
                System.out.println("siteCode :: "+siteCode);
				System.out.println("xmlString  !!!!"+xmlString);
				retString = saveData(siteCode,xmlString,conn);
				System.out.println("retString ::::::"+retString);
				
                
                
						
		
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
		
		
		
		return retString;
		
	}
	
	
	
	
	private String saveData(String siteCode,String xmlString, Connection conn) throws ITMException
	{
		System.out.println("saving data...........");
		InitialContext ctx = null;
		String retString = null;
		MasterStatefulLocal masterStateful = null; // for ejb3
		try
		{
			AppConnectParm appConnect = new AppConnectParm();
			ctx = new InitialContext(appConnect.getProperty());
			masterStateful = (MasterStatefulLocal)ctx.lookup("ibase/MasterStatefulEJB/local");
			System.out.println("-----------masterStateful------- " + masterStateful);
			String [] authencate = new String[2];
			authencate[0] = "";
			authencate[1] = "";
			System.out.println("xmlString to masterstateful [" + xmlString + "]");
			retString = masterStateful.processRequest(authencate, siteCode, true, xmlString,true,conn);
			System.out.println("--retString - -"+retString);
		}
		catch(ITMException itme)
		{
			System.out.println("ITMException :CreateDistOrder :saveData :==>");
			throw itme;
		}
		catch(Exception e)
		{
			e.printStackTrace();
			System.out.println("Exception :CreateDistOrder :saveData :==>");
			throw new ITMException(e);
		}
		return retString;
	}
	
	

}
