package gov.maine.node.client;

//import gov.epa.cdx.axis.v10.client.NodeRequestor;
//import gov.epa.cdx.axis.v10.vo.NodeDocument;
//import java.security.Security;

import java.io.*;
import java.net.*;
import java.util.*;
import java.lang.*;
import java.sql.*;
import oracle.jdbc.driver.*;
import oracle.xml.sql.query.OracleXMLQuery;
import oracle.xml.parser.v2.*;
import oracle.xml.parser.schema.*;
import org.w3c.dom.*;
import oracle.jdbc.OracleTypes.*;
import oracle.sql.*;
import java.util.ArrayList;
import java.util.Iterator;

/*
 * This program will check the submit_job_queue and invoke the submit web method 
 * of the destination node to submit the document
 */

public class SubmitListener
{
  static String connect_t =  "jdbc:oracle:thin:@<host_name>:<port>:<oracle_sid>";
  static String username_t = "<schem_user>";
  static String password_t = "<user_password>";
  static String db = "<oracle_sid>";

/*  static
  {
     //this adds SSL provider
     //for the client we are going to add a JSSE Provider
     Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
     //we need to set the SSLSocketFactory to ignore invalid server side certs
     Security.setProperty( "ssl.SocketFactory.provider", "gov.epa.state.sample.DummySSLSocketFactory");
  }
*/
  public ArrayList submitListener() throws Exception
  {
     ArrayList eventList = new ArrayList(12);
     String event = null;
     Connection dbConnection = null;
     OracleCallableStatement cstmt=null;
     String queue_name = "SUBMIT_JOB_QUEUE";
     String trans_id = null;
     String sql_stmt = null;
     PreparedStatement ps=null;
     ResultSet rs = null;
     boolean valid_message = true;
     String returnURL_t = null;
     String document_content_t = null;
     String document_name_t = null;
     String document_type_t = null;
     NetworkNodeStub requestor = null;
     String transactionId = null;
     
     try
     {
        dbConnection = createDBConnection(db);
        dbConnection.setAutoCommit(false);

        while (valid_message)
        {
        // setup and execute the call to the PL/SQL stored procedure.

          cstmt = (OracleCallableStatement) dbConnection.prepareCall("{call SUBMIT_DEQUEUE(?,?)}");
          cstmt.setString(1,queue_name);
          cstmt.registerOutParameter(2,Types.VARCHAR);
          cstmt.execute();
          trans_id = cstmt.getString(2);
          cstmt.close();
          dbConnection.commit();

          if (trans_id.equals("-999")) 
          {
            eventList.add("End of Queue.");
            valid_message = false;
          }
          else 
          {
// use transaction id to get document_content, document_name, document_type
            sql_stmt = "SELECT document_content, document_name, document_type "; 
            sql_stmt = sql_stmt + "from wdocument a, incoming_download b ";
            sql_stmt = sql_stmt + "where a.incoming_download_id = b.incoming_download_id and b.server_transaction_id = ?";
            ps = dbConnection.prepareStatement(sql_stmt);

            ps.setString(1,trans_id);
            rs = ps.executeQuery();
            if (!rs.next())
            {
              throw new Exception("Invalid Transaction Id");
            }           
            else
            {
              document_content_t = rs.getString("document_content");
              document_name_t = rs.getString("document_name");
              document_type_t = rs.getString("document_type");
              ps.close();
              rs.close();
            }

            sql_stmt = "SELECT returnURL from incoming_Solicit where server_transaction_id = ?"; 
            ps = dbConnection.prepareStatement(sql_stmt);
            ps.setString(1,trans_id);
            rs = ps.executeQuery();
            if (!rs.next())
            {
              throw new Exception("Invalid returnURL for Transaction Id");
            }           
            else
            {
              returnURL_t = rs.getString("returnURL");
              ps.close();
              rs.close();
            

              // check the url format.
          //    URL url = validateAndReturnURL(returnURL_t);

              // instantiate a new NetworkNodeStub with the given URL.
              requestor = new NetworkNodeStub(returnURL_t);
            
              // authenticate with the node and recieve a token.
              String token = requestor.authenticate("<node_user_account>","<user_password>", "password");
              // place the information into a NodeDocument array.
              NodeDocument[] docArray = new NodeDocument[1];
              NodeDocument doc = new NodeDocument();
              doc.setName(document_name_t);
              doc.setType(document_type_t);
              byte [] content = document_content_t.getBytes();
              doc.setContent(content);
              docArray[0] = doc;

              // For testing, the transaction Id returned by the client needs to 
              // be inserted into the outgoing_solicit table.  This simulates a
              // call to the Solicit method by the included Java client.
              // null can be substituted for trans_id for testing purposes.

              transactionId = requestor.submit(token, trans_id, "TEST", docArray);
              eventList.add(transactionId);
            }
          } //else block executed if transId <> -999
        }// while valid message block.
     }

     catch (Exception e)
     {
         try 
         {
            dbConnection.rollback();
            if (cstmt != null)
            {
               cstmt.close();
            }
            if (dbConnection != null)
            {
               dbConnection.close();
            }
         }
         catch (Exception e1)
         {
 
         }
         event = e.getClass() + e.getLocalizedMessage();
         eventList.add(event);
       //  throw new Exception(point);
         throw e;
     }
     dbConnection.close();
     return eventList;
  }

   public Connection createDBConnection(String source) throws Exception
   {
       DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
       Connection dbConnection = DriverManager.getConnection(connect_t, username_t, password_t );
       return dbConnection;
   }

   private static URL validateAndReturnURL(String URLString)
   {
      URL url = null;
      try
      {
        url = new URL(URLString);
      }
      catch (MalformedURLException ex)
      {
        new Exception(URLString + " is malformed URL. Fatal exception.");
      }

      return url;
   }

   public static void main(String[] args) throws Exception 
   {
      SubmitListener sl = new SubmitListener();
      System.out.println("call the SubmitListener.");

      ArrayList list = sl.submitListener();
      Iterator i = list.iterator();
      while (i.hasNext())
      {
         String element = (String) i.next();
         System.out.println(element);
      }
   }



}