/**
 * PURPOSE : Post Save Logic implementation for Replenishment component.
 * AUTHOR : Chaitali Parab 15/11/11
 */
package ibase.webitm.ejb.wms;

import ibase.webitm.utility.*;
import ibase.webitm.ejb.*;
import ibase.webitm.utility.ITMException;

import java.rmi.RemoteException;
import java.sql.*;
import java.util.TreeMap;

import javax.ejb.Stateless; 
import org.w3c.dom.*;

import ibase.webitm.ejb.dis.DistCommon;
import ibase.webitm.ejb.wms.ReplIssConf;

@Stateless 
public class ReplIssPos extends ValidatorEJB implements ReplIssPosRemote, ReplIssPosLocal
{
	public String postSave( String domString, String tranId,String editFlag, String xtraParams, Connection conn ) throws RemoteException,ITMException
	{
		System.out.println("--->postSave called xml str["+domString+"]");
		String retString = "";
		String forcedFlag = "false" ;

		String replOrder = "";
		String sql = "";
		String orderType = "";
		String locCodeTo = "";
		String lotSl = "";
		//Changed by sumit on 09/10/12 start 
		String ptcn = "";
		String errString = "";
		String locCodeTwo = "";
		//Changed by sumit on 09/10/12 end 
		PreparedStatement pstmt = null;
		ResultSet rs = null ;

		NodeList parentNodeList = null;
		Node parentNode = null;
		int parentNodeListLength = 0;

		int totalRow = 0;
		int selectedRow = 0;
		int ctr = 0;
		int locCtr = 0;
		Document dom = null;
		GenericUtility genericUtility = GenericUtility.getInstance();
		boolean isConn= false;
		try
		{
			dom = genericUtility.parseString(domString);
			NodeList detail3List = dom.getElementsByTagName("Detail3");
			if(detail3List != null && detail3List.getLength() > 0)
			{
				System.out.println("Detail3 length = "+detail3List.getLength());

				replOrder = GenericUtility.getInstance().getColumnValueFromNode("repl_order", dom.getElementsByTagName("Detail1").item(0));
				//Changed by sumit on 09/10/12 for taking value of locCodeto 
				locCodeTwo = GenericUtility.getInstance().getColumnValueFromNode("loc_code__to", dom.getElementsByTagName("Detail3").item(0));
				System.out.println(" loc_code__to ["+locCodeTwo+"]");
				sql = "select count(*) from repl_ord_det where repl_order = ?";
				pstmt = conn.prepareStatement(sql);
				pstmt.setString( 1, replOrder);						
				rs = pstmt.executeQuery();	
				if( rs.next() )
				{
					totalRow = rs.getInt(1);
				}
				rs.close();
				rs = null;
				pstmt.close();
				pstmt = null;					
				System.out.println("======>totalRow : "+totalRow);

				sql = "select count(*) from repl_iss_det where repl_order = ?";
				pstmt = conn.prepareStatement(sql);
				pstmt.setString( 1, replOrder);						
				rs = pstmt.executeQuery();	
				if( rs.next() )
				{
					selectedRow = rs.getInt(1);
				}
				rs.close();
				rs = null;
				pstmt.close();
				pstmt = null;
				//Added By Mahesh Patidar on 31/07/12
				//Changed by sumit on 09/10/12 getting ptcn value 
				//sql = "select order_type from repl_ord_hdr where repl_order = ?";
				sql = 	" SELECT ROH.ORDER_TYPE, WID.PTCN FROM REPL_ORD_HDR ROH, WAVE_TASK_DET WID WHERE ROH.REPL_ORDER = ? " +
						" AND ROH.REPL_ORDER = WID.REF_ID ";
				pstmt = conn.prepareStatement(sql);
				pstmt.setString( 1, replOrder);						
				rs = pstmt.executeQuery();	
				if( rs.next() )
				{
					orderType = rs.getString(1);
					ptcn = rs.getString(2);
				}
				rs.close();
				rs = null;
				pstmt.close();
				pstmt = null;
				System.out.println("orderType="+orderType);//Changed by sumit on 09/10/12 calling report start.
				if("D".equals(orderType) || "L".equals(orderType))
				{
					System.out.println("Calling Jasper Report ***************************************");
					errString = generateReport(replOrder, ptcn, locCodeTwo, conn,xtraParams);
					if( errString.trim().length() == 0)
					{
						System.out.println(" report genetrated successfully ");
					}
					
				}
				//Changed By Mahesh Patidar on 07/08/12
				//changed condition by Kunal Mandhre on 31/08/12
				if ("A".equalsIgnoreCase(orderType) || "Q".equalsIgnoreCase(orderType) || "E".equalsIgnoreCase(orderType) || "T".equalsIgnoreCase(orderType))
				{
					System.out.println("for case repl::::");
					parentNodeList = dom.getElementsByTagName("Detail4");
					parentNodeListLength = parentNodeList.getLength();
					locCtr = 0;
					if ( parentNodeListLength > 0)
					{
						for(ctr = 0; ctr < parentNodeListLength ; ctr++ )
						{
							parentNode = parentNodeList.item(ctr);
							locCodeTo = genericUtility.getColumnValueFromNode("loc_code__to", parentNode);
							lotSl = genericUtility.getColumnValueFromNode("lot_sl", parentNode);

							System.out.println("Location Code["+locCodeTo+"] and lot_sl["+lotSl+"] and tran_id["+tranId+"]");
							//Commented By Mahesh Patidar on 07/08/12
							//					parentNodeList = dom.getElementsByTagName("Detail2");
							//					parentNodeListLength = parentNodeList.getLength();
							//					parentNode = parentNodeList.item(0);
							//					tranId1 = genericUtility.getColumnValueFromNode("tran_id", parentNode);
							//Commented By Mahesh Patidar 
							if (locCodeTo != null && locCodeTo.trim().length() > 0)
							{
								locCtr++;
								sql = "update repl_iss_det set loc_code__to = ? where tran_id = ?  and lot_sl = ? ";
								pstmt = conn.prepareStatement(sql);
								pstmt.setString( 1, locCodeTo);		
								pstmt.setString( 2, tranId);		
								pstmt.setString( 3, lotSl);		
								pstmt.executeUpdate();	
								pstmt.close();
								pstmt = null;
							}
							//if(totalRow == selectedRow)
							if(totalRow == locCtr)
							{
								System.out.println("=======>totalRow [" + totalRow + "] locCtr [" + locCtr + "]");
								ReplIssConf replIssConf = new ReplIssConf();
								retString = replIssConf.confirm(tranId, xtraParams, forcedFlag, conn, isConn);
								System.out.println("retString[" +retString +"]");
								if (retString.indexOf("REPISSCONF") > -1)
								{
									retString = "";
								}
								if ( retString != null && retString.length() > 0 )
								{
									throw new Exception("Exception while calling confirm for tran  Id:["+tranId+"]");
								}
							}
							else
							{
								System.out.println("All rows are not selected");				
							}
						}
					}
				}
				else
				{
					//End Changed BY Mahesh Patidar
					//Ended By Mahesh Patidar
					if(totalRow == selectedRow)
					{
						System.out.println("=======>totalRow == selectedRow");
						ReplIssConf replIssConf = new ReplIssConf();
						retString = replIssConf.confirm(tranId, xtraParams, forcedFlag, conn, isConn);
						System.out.println("retString[" +retString +"]");
						if ( retString != null && retString.length() > 0 )
						{
							throw new Exception("Exception while calling confirm for tran  Id:["+tranId+"]");
						}
					}
					else
					{
						System.out.println("All rows are not selected");				
					}
				}
			}
		}
		catch(Exception e)
		{
			e.printStackTrace();
			throw new ITMException(e);
		}
		finally
		{
			try
			{
				if( rs != null )
				{
					rs.close();
					rs = null;
				}
				if( pstmt != null )
				{
					pstmt.close();
					pstmt = null;
				}
			}
			catch(Exception e)
			{
				System.err.println("Exception :ReplIssPos :\n"+e.getMessage());
				e.printStackTrace();
				throw new ITMException(e);
			}
		}
		return retString;
	}
	//Changed by sumit on 09/10/12 generating report start.
	private String generateReport(String replOrder,String ptcn, String locCodeTo, Connection conn,String xtraParams ) throws ITMException
    {
    	String errString ="";
    	String printMode = "";
    	String outputFilename = "";
    	TreeMap argMap = null;
    	DistCommon discommon = new DistCommon();
    	GenericUtility genericUtility = GenericUtility.getInstance();
    	try
    	{    		
    		//String printerStr  = discommon.getDisparams("999999","STOCK_TO_DOCK_PRINTER",conn);
    		System.out.println("PRINT MODE CALLED");
    		String chgUser = genericUtility.getValueFromXTRA_PARAMS(xtraParams, "loginCode");								
			System.out.println(" printerStr ->["+locCodeTo+"]");				
			if(locCodeTo.trim().length() > 0)
			{					
				String reportObjName = discommon.getDisparams("999999","STOCK_TO_DOCK_OBJ_NAME",conn);					
				String reportSavetype = "NATIVE";					
				ibase.webitm.reports.utility.JasperReportGenerator jrGenerator = new ibase.webitm.reports.utility.JasperReportGenerator();
				String xsdString ="<Arguments>" +
							"<Argument id=\"REPLORDER\" name=\"REPLORDER\">" +
							"<argType>java.lang.String</argType>" +
							//"<value>"+ptcnList.get(i)+"</value>" +
							"<value>"+replOrder+"</value>" +
							"</Argument>" +
							"<Argument id=\"PTCN\" name=\"PTCN\">" +
							"<argType>java.lang.String</argType>" +
							//"<value>"+ptcnList.get(i)+"</value>" +
							"<value>"+ptcn+"</value>" +
							"</Argument>" +
							"<Argument id=\"x_path\" name=\"x_path\">" +
							"<argType>java.lang.String</argType>" +
							"<value>/DocumentRoot/wave_task_main</value>" +
							"</Argument>" +
							"<Argument id=\"design_source\" name=\"design_source\">" +
							"<argType>java.lang.String</argType>" +
							"<value>wave_task_main.jrxml</value>" +
							"</Argument>" +
							"<Argument id=\"data_source\" name=\"data_source\">" +
							"<argType>java.lang.String</argType>" +
							"<value>SQL</value>" +
							"</Argument>" +
							"<Argument id=\"bind_type\" name=\"bind_type\">" +
							"<argType>java.lang.Integer</argType>" +
							"<value>0</value>" +
							"</Argument>" +
							"<Argument id=\"report_type\" name=\"report_type\">" +
							"<argType>java.lang.String</argType>" +
							"<value>JASPER</value>" +
							"</Argument>" +
							"<Argument id=\"report_save_type\" name=\"report_save_type\">" +
							"<argType>java.lang.String</argType>" +
							//Changed by sumit on 07/09/12  changed NATIVE to PDF
							//"<value>NATIVE</value>" +									
							"<value>"+reportSavetype+"</value>" +
							"</Argument>" +
							"</Arguments>";
				System.out.println(" XSD parser **->["+xsdString+"]");						
				errString = jrGenerator.printReport(reportObjName, xsdString, chgUser, locCodeTo, 1, conn);			
					
				//}
				System.out.println(" PRINTING task completed--------**------->");
			}			
    	}
    	catch (Exception e)
    	{
    		e.printStackTrace();
    		throw new ITMException(e);
    	}
    	
    	return errString;
    }
	//Changed by sumit on 09/10/12 generating report end.
}
