
import java.util.logging.Logger;

// mySQL access
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Driver;
import java.sql.ResultSet;
import java.sql.Statement;
import java.sql.SQLException;
import java.sql.Array;
// import javax.sql.*; needed if using DataSource instead of DriverManager for DB-connections

import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;

import java.util.Enumeration;
import java.util.List;
import java.util.LinkedList;
import java.util.Set;
import java.util.HashSet;
import java.util.ArrayList;




public class ResolverByObsCoreDb
{
   private static final Logger LOGGER = Logger.getLogger(ResolverByObsCoreDb.class.getName());

   private static final Settings settings = Settings.getInstance();
   public static Settings.DBConn dbconn = settings.dbConn;
   private static final String DB_DRIVER = "org.postgresql.Driver";

   private Connection conn;
   private Statement  st;
   private ResultSet  res;


   ResolverByObsCoreDb() throws ClassNotFoundException
   {
      conn = null;
      st   = null;
      res  = null;
      //LOGGER.info("Loading DB driver: " + DB_DRIVER);
      //Class.forName(DB_DRIVER);
   }


   public String[] queryAccessUrlAndObsCollection(String pubdid)
   {
      String obsPubdid =  pubdid;

      String TheQuery = "SELECT access_url,obs_collection FROM obscore "
         + "WHERE obs_publisher_did = \'"+ obsPubdid +"\'";
      LOGGER.info(TheQuery);

      String[] results = new String[2];

      LOGGER.info("Connecting to: " + dbconn.uri() + " with optional user/pwd: " + dbconn.userName() + " / " + dbconn.password() );

      try(
            Connection conn = DriverManager.getConnection(dbconn.uri(), dbconn.userName(), dbconn.password());
            Statement  st   = conn.createStatement();
            ResultSet  res  = st.executeQuery(TheQuery);)
      {
         //res = doQuery(TheQuery);

         if(res == null)
         {
            LOGGER.info("Pubdid not in the db: " + pubdid);
            return null;
         };

         int count = 0;
         while (res.next())
         {
            count++;
            results[0] = res.getString("access_url").strip();
            results[1] = res.getString("obs_collection").strip();
         }

         assert(count == 1);// pubdid is unique

      }
      catch (SQLException se)
      {
         logSqlExInfo(se);
         se.printStackTrace();
      }
/*      catch (ClassNotFoundException e)
      {
         LOGGER.info("DB driver "+ DB_DRIVER +" not found: " + e.getMessage());
         e.printStackTrace();
      }
            finally
              {
              closeAll();
              }
              */
      return results; 
   }


   /*
      private void closeAll() {

      try {
      if(res  != null ) res.close();
      if(st   != null ) st.close();
      if(conn != null ) conn.close();
      } catch (Exception e){
   // FIXME print ?warning? into Glassfish SQLdriver close failed
   e.printStackTrace();
      }

      }
      */


   private void logSqlExInfo(SQLException se)
   {
      LOGGER.info("SQLState : " + se.getSQLState());
      LOGGER.info("ErrorCode: " + se.getErrorCode());
      LOGGER.info("Message  : " + se.getMessage());
      Throwable t = se.getCause();
      while(t != null) {
         LOGGER.info("Cause: " + t);
         t = t.getCause();
      }
   }


   /*
      private ResultSet doQuery(String TheQuery) throws SQLException, ClassNotFoundException
      {
   /* https://docs.oracle.com/javase/tutorial/jdbc/basics/connecting.html :
    * Any JDBC 4.0 drivers that are found in your class path are automatically loaded.
    * (However, you must manually load any drivers prior to JDBC 4.0 with the method
    * Class.forName.)
    * /
//    Class.forName(DB_DRIVER);
   /* OR
    * DriverManager.registerDriver(new org.postgresql.Driver());
    * LOGGER.info(getClasspathString());
    * LOGGER.info(getRegisteredDriverList());
    * /

    LOGGER.info("Connecting to: " + dbconn.uri() + " with optional user/pwd: " + dbconn.userName() + " / " + dbconn.password() );

//    Connection conn = DriverManager.getConnection(dbconn.uri(), dbconn.userName(), dbconn.password());

    Statement  st   = conn.createStatement();

    ResultSet  res  = st.executeQuery(TheQuery);

    return res;
      }
   // Retursn the list of JDBC Drivers loaded by the caller's class loader
   private String getRegisteredDriverList()
   {
   StringBuffer drvList = new StringBuffer("getRegisteredDriverList:\r\n");
   for (Enumeration e = DriverManager.getDrivers();
   e.hasMoreElements(); )
   {
   Driver d = (Driver) e.nextElement();
   String driverClass = d.getClass().getName();
   drvList.append(driverClass).append("\r\n");	
   }
   return drvList.toString();
   }

   /*
   public String getClasspathString() {
   StringBuffer classpath = new StringBuffer("getClasspathString:\r\n");
   ClassLoader applicationClassLoader = this.getClass().getClassLoader();
   if (applicationClassLoader == null) {
   applicationClassLoader = ClassLoader.getSystemClassLoader();
   }
   URL[] urls = ((URLClassLoader)applicationClassLoader).getURLs();
   for(int i=0; i < urls.length; i++) {
   classpath.append(urls[i].getFile()).append("\r\n");
   }

   return classpath.toString();
   }
   */


}
