/*******************************************
    Title   ExpiryProcess 
    Developed  Date                3/9/2009
Modified By Ashwin on 05-Aug-10 
// For Getting Processing Sites from Schedulers ActualParameter Instead of DISPARM
********************************************/
package ibase.webitm.ejb.sys;
import java.util.*;
import java.sql.*;
import ibase.system.config.ConnDriver;
import org.apache.axis.Constants;
import org.apache.axis.client.Call;
import org.apache.axis.client.Service;
import org.apache.axis.encoding.XMLType;
import javax.xml.rpc.ParameterMode;
import ibase.utility.CommonConstants;
import java.util.*;
import ibase.webitm.utility.ITMException;
import java.rmi.RemoteException;
import org.w3c.dom.*; 
import ibase.webitm.utility.GenericUtility ;
import ibase.scheduler.utility.interfaces.Schedule;
import java.util.Date;
import java.text.SimpleDateFormat;
//import org.apache.commons.logging.LogFactory;
public class ExpiryProcess implements Schedule
{
    ibase.utility.GenericUtility genericUtility = new ibase.utility.GenericUtility();    
    Object[] aobj = new Object[4];        
  //Added By Manoj dtd 05/11/2012 implement abstract method	
	public String schedulePriority( String wrkflwPriority )throws Exception
	{
		return "";
	}
    public String schedule( HashMap map )throws RemoteException, ITMException
    {
        return "";
    }
    public String schedule( String scheduleParamXML )throws RemoteException, ITMException
    {
				System.out.println("\n\n\n\n\n ::::::::::::::::::: ExpiryProcess :::::::::::::::::::::::");
        PreparedStatement pstmt = null ;
        ResultSet rs = null ; 
        Connection conn=null;    
        String sql="";
        String userInfoList = null;
        String isIntractive = null;
        String objName = null;        
        String varValue  = "",varvalue2 = "",varvalue1="";
        String addlValue =null;
        //String addlValue = "";    
        Timestamp  frDate = null ,currDate=null,addlValueTm =null,currAppTime = null;//addlValue = null;
        SimpleDateFormat currAppdate = null;
        String lsFromdateStr ="",siteCode = "",retString="",xtraParams="",despid = "",drnoteDateStr = "";
        Date lsFromdateDt = null,dateValue = null;        
        String freshDescr="";
        String locCode="" ,expLoc = "",nearExpLoc = "" ;
        StringBuffer filterString = new StringBuffer();            
        StringBuffer fltrArg = null;
        StringTokenizer stringTokenizer = null;
        String varName = "";

        double timdifferance = 0.00;
        try
        {
            if( conn == null )
            {
                ConnDriver connDriver = new ConnDriver();
                conn = connDriver.getConnectDB("DriverITM");
                conn.setAutoCommit(false);        
            }
            
            System.out.println(" scheduleParamXML  [" + scheduleParamXML + "]");
            Document userInfoDom = new ibase.utility.GenericUtility().parseString( scheduleParamXML );            
            NodeList paramList = userInfoDom.getElementsByTagName( "SCHEDULE" );
            Node currDetail = null ;            
            int noOfParam = paramList.getLength();            
            for( int paramCnt = 0; paramCnt < noOfParam ; paramCnt++ )
            {
                currDetail = paramList.item(paramCnt);
                siteCode = currDetail.getAttributes().getNamedItem("id").getNodeValue();
            }            
            //----- Changes Start By Ashwin On 05-Aug-10 - Begin
						NodeList parentNodeList = null,childNodeList = null;
						Node parentNode = null,childNode = null;
						String DisparmSites = "";
						int childNodeListLength = 0;
						String childNodeName = null;

						parentNodeList = userInfoDom.getElementsByTagName("ACTUALPARAMETERS");

						parentNode = parentNodeList.item(0);
						childNodeList = parentNode.getChildNodes();
						childNodeListLength = childNodeList.getLength();
						for(int ctr = 0; ctr < childNodeListLength; ctr++)
						{
							childNode = childNodeList.item(ctr);
							childNodeName = childNode.getNodeName();
							
							if(childNodeName!=null && !"#text".equalsIgnoreCase(childNodeName))
							{
								
								if(ctr==0)
								{
									DisparmSites=childNode.getFirstChild().getNodeValue();
								}
							}
						}
						System.out.println("\n\n :::: Disparm Sites["+DisparmSites+"]");

						//----- Changes End By Ashwin On 05-Aug-10 - End

						// code to be migrate                
            java.sql.Timestamp drnoteDate = new java.sql.Timestamp( System.currentTimeMillis() );
            drnoteDateStr = genericUtility.getValidDateString(drnoteDate.toString(),genericUtility.getDBDateFormat(),genericUtility.getApplDateFormat());
                
            sql="select var_value,descr "
                +"from disparm "
                + "where prd_code = '999999' "
                + "and var_name = 'ALLOC_FGLOC' " ;
            pstmt = conn.prepareStatement( sql );    
            rs = pstmt.executeQuery();
            if( rs.next() )         
            {    
                locCode = rs.getString("var_value") == null?"":rs.getString("var_value");
                freshDescr = rs.getString("descr") == null?"":rs.getString("descr") ;
            }
            rs.close();
            pstmt.close();
            rs=null;
            pstmt = null;
            sql="select var_value "
                +"from disparm "
                + "where prd_code = '999999' "
                + "and var_name = 'NEAREXP_LOC' " ;
            pstmt = conn.prepareStatement( sql );    
            rs = pstmt.executeQuery();
            if( rs.next() )         
            {
                nearExpLoc = rs.getString("var_value")==null?"":rs.getString("var_value");
            }
            rs.close();
            pstmt.close();
            rs=null;
            pstmt = null;

            sql="select var_value "
                +"from disparm "
                + "where prd_code = '999999' "
                + "and var_name = 'EXP_LOC' " ;
            pstmt = conn.prepareStatement( sql );    
            rs = pstmt.executeQuery();
            if( rs.next() )         
            {
                expLoc = rs.getString("var_value")==null?"":rs.getString("var_value");
            }
            rs.close();
            pstmt.close();
            rs=null;
            pstmt = null;
            // end of code
            //sql = "select site_code from  site " ;
						
						//-- Commented By Ashwin On 05-Aug-10 - Begin
						// So as to get Sites from scheduler ActualParameter Instead of DISPLARM
            /*sql = " SELECT VAR_VALUE  FROM DISPARM WHERE PRD_CODE='999999' AND VAR_NAME = 'AUTONEARCHARGESITE' " ;
            pstmt = conn.prepareStatement(sql);
            rs = pstmt.executeQuery();
            if(rs.next())
            {
                varName = rs.getString("var_value");
            }
            rs.close();
            pstmt.close();
            rs=null;
            pstmt = null;    
            stringTokenizer = new  StringTokenizer(varName ,",");
						*/
					 //Changes Done by Ashwin On 05-Aug-10 -  End

					stringTokenizer = new  StringTokenizer(DisparmSites ,",");
          while(stringTokenizer.hasMoreElements())
          {
							filterString.append(stringTokenizer.nextToken()).append("\t");            
							filterString.append(drnoteDateStr).append("\t");
							filterString.append("00").append("\t");
							filterString.append("ZZ").append("\t");                
							//filterString.append("").append("\t");// changes for nearexpiry and expiry 
							fltrArg = new StringBuffer( filterString.toString() );
							fltrArg.append(nearExpLoc).append("\t"); // nearexpiery to nearexppiery 
							fltrArg.append(nearExpLoc).append("\t");
							fltrArg.append("E").append("\t");
							fltrArg.append("\n");
							retString = callNvo( fltrArg.toString(), "near_expiry", "pr_default_1", conn );                    
							fltrArg = new StringBuffer( filterString.toString() );
							fltrArg.append(locCode).append("\t"); //fresh to fresh using nearExpieryLocation
							fltrArg.append(locCode).append("\t");
							fltrArg.append("N").append("\t");
							fltrArg.append("\n");
							retString = callNvo( fltrArg.toString(), "near_expiry", "pr_default_1", conn );    
							fltrArg = new StringBuffer( filterString.toString() );
							fltrArg.append(locCode).append("\t"); //fresh to fresh using ExpieryLocaltion
							fltrArg.append(locCode).append("\t");
							fltrArg.append("E").append("\t");
							fltrArg.append("\n");
							retString = callNvo( fltrArg.toString(), "near_expiry", "pr_default_1", conn );    
							filterString.setLength(0);
          }        
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }
        return "";
    } // end of schedule 
    public String callNvo( String filterData, String objName, String serviceCode, Connection conn )  throws ITMException
    {
        String methodName = "";
        String retString = "";        
        String serviceURI = "";
        String actionURI = "";
        String selectSql = "" , selectSqlSec = "" ;
        String businessObj = "",xtraParams = "";    
        Statement stmt = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        try
        {
                    
            //businessObj = "nvo_bo_finance_charge_calc";
            selectSql = "SELECT comp_name FROM SYSTEM_EVENTS WHERE OBJ_NAME = ? AND service_code =  ?  ";
            System.out.println("\nselectSql :: "+selectSql);
            pstmt = conn.prepareStatement(selectSql);
            pstmt.setString(1,objName);
            pstmt.setString(2,serviceCode);
            rs = pstmt.executeQuery();    
            //stmt = conn.createStatement();
            //rs = stmt.executeQuery(selectSql);
            if ( rs.next() )
            {
                businessObj = rs.getString( "comp_name" );
            }
            System.out.println("businessObj :: "+businessObj);
            rs.close();            
            pstmt.close();
            rs = null;
            pstmt = null;
            selectSqlSec = "SELECT SERVICE_URI, METHOD_NAME FROM SYSTEM_EVENT_SERVICES WHERE SERVICE_CODE = ? ";
            System.out.println("\nselectSql :: "+selectSqlSec);
            pstmt = conn.prepareStatement(selectSqlSec);
            pstmt.setString(1,serviceCode);
            rs = pstmt.executeQuery();    
            //rs = stmt.executeQuery(selectSql);
            if ( rs.next() )
            {
                serviceURI = rs.getString( "SERVICE_URI" );
                methodName = rs.getString( "METHOD_NAME" );
            }            
            actionURI = "http://NvoServiceurl.org/"+methodName;            
            System.out.println("\n actionURI :: "+actionURI);
           Service service = new Service();
           Call call = ( Call )service.createCall();
           call.setTargetEndpointAddress(new java.net.URL(serviceURI));            

            call.setOperationName( new javax.xml.namespace.QName("http://NvoServiceurl.org", methodName ) );
            call.setUseSOAPAction(true);
            call.setSOAPActionURI(actionURI); 
            Object[] aobj = new Object[4];
            
            call.addParameter( new javax.xml.namespace.QName("http://NvoServiceurl.org", "component_name"), XMLType.XSD_STRING, ParameterMode.IN);
            call.addParameter( new javax.xml.namespace.QName("http://NvoServiceurl.org", "tab_xml_data_1"), XMLType.XSD_STRING, ParameterMode.IN);
            call.addParameter( new javax.xml.namespace.QName("http://NvoServiceurl.org", "dummy"), XMLType.XSD_STRING, ParameterMode.IN);
            call.addParameter( new javax.xml.namespace.QName("http://NvoServiceurl.org", "xtra_params"), XMLType.XSD_STRING, ParameterMode.IN);
            
            aobj[0] = new String(businessObj);
            aobj[1] = new String(filterData);
            aobj[2] = new String( "" );
            aobj[3] = new String( xtraParams );// passed blank as It can not be created from scheduler
            
            call.setReturnType(XMLType.XSD_STRING);
            retString = (String)call.invoke( aobj );
            System.out.println("Return value [" + retString +"]");
        }
        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)
            { e.printStackTrace();}
        }
        return retString ;
    }
}