/*
 * The contents of this file are subject to the Mozilla Public License Version 1.1
 * (the "License"); you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at <http://www.mozilla.org/MPL/>.
 * 
 * Software distributed under the License is distributed on an "AS IS" basis, WITHOUT
 * WARRANTY OF ANY KIND, either express or implied. See the License for the specific
 * language governing rights and limitations under the License.
 * 
 * The Original Code is the Venice Web Communities System.
 * 
 * The Initial Developer of the Original Code is Eric J. Bowersox <erbo@silcom.com>,
 * for Silverwrist Design Studios.  Portions created by Eric J. Bowersox are
 * Copyright (C) 2003 Eric J. Bowersox/Silverwrist Design Studios.  All Rights Reserved.
 * 
 * Contributor(s): 
 */
package com.silverwrist.dynamo.index;

import java.io.*;
import java.sql.*;
import java.util.*;
import com.silverwrist.util.*;
import com.silverwrist.dynamo.except.*;
import com.silverwrist.dynamo.iface.*;

class IndexOps_mysql extends IndexOps
{
  /*--------------------------------------------------------------------------------
   * Constructor
   *--------------------------------------------------------------------------------
   */

  public IndexOps_mysql(DBConnectionPool pool)
  {
    super(pool);

  } // end constructor

  /*--------------------------------------------------------------------------------
   * Abstract implementations from class IndexOps
   *--------------------------------------------------------------------------------
   */

  String getAnalyzerClassName(int ndx) throws DatabaseException
  {
    Connection conn = null;
    PreparedStatement stmt = null;
    ResultSet rs = null;
    try
    { // get a connection
      conn = getConnection();

      // create and execute the statement
      stmt = conn.prepareStatement("SELECT analyzer FROM ndx_main WHERE ndxid = ?;");
      stmt.setInt(1,ndx);
      rs = stmt.executeQuery();
      if (rs.next())
	return rs.getString(1);
      else
	return null;

    } // end try
    catch (SQLException e)
    { // translate to a general DatabaseException
      throw generalException(e);

    } // end catch
    finally
    { // shut everything down
      SQLUtils.shutdown(rs);
      SQLUtils.shutdown(stmt);
      SQLUtils.shutdown(conn);

    } // end finally

  } // end getAnalyzerClassName

  String[] listFiles(int ndx) throws DatabaseException
  {
    Connection conn = null;
    PreparedStatement stmt = null;
    ResultSet rs = null;
    try
    { // get a connection
      conn = getConnection();

      // set up and execute the statement
      stmt = conn.prepareStatement("SELECT name FROM ndx_files WHERE ndxid = ? ORDER BY name;");
      stmt.setInt(1,ndx);
      rs = stmt.executeQuery();

      // create the return value
      ArrayList tmp = new ArrayList();
      while (rs.next())
	tmp.add(rs.getString(1));
      String[] rc = new String[tmp.size()];
      tmp.toArray(rc);
      return rc;

    } // end try
    catch (SQLException e)
    { // translate to a general DatabaseException
      throw generalException(e);

    } // end catch
    finally
    { // shut everything down
      SQLUtils.shutdown(rs);
      SQLUtils.shutdown(stmt);
      SQLUtils.shutdown(conn);

    } // end finally

  } // end listFiles

  long getModTime(int ndx, String file) throws DatabaseException
  {
    Connection conn = null;
    PreparedStatement stmt = null;
    ResultSet rs = null;
    try
    { // get a connection
      conn = getConnection();

      // create and execute the statement
      stmt = conn.prepareStatement("SELECT mtime FROM ndx_files WHERE ndxid = ? AND name = ?;");
      stmt.setInt(1,ndx);
      stmt.setString(2,file);
      rs = stmt.executeQuery();
      if (rs.next())
	return rs.getLong(1);
      else
	return -1;

    } // end try
    catch (SQLException e)
    { // translate to a general DatabaseException
      throw generalException(e);

    } // end catch
    finally
    { // shut everything down
      SQLUtils.shutdown(rs);
      SQLUtils.shutdown(stmt);
      SQLUtils.shutdown(conn);

    } // end finally

  } // end getModTime

  void setModTime(int ndx, String file, long mtime) throws DatabaseException
  {
    Connection conn = null;
    PreparedStatement stmt = null;
    Statement stmt2 = null;
    try
    { // get a connection
      conn = getConnection();

      // lock the table
      stmt2 = conn.createStatement();
      stmt2.executeUpdate("LOCK TABLES ndx_files WRITE;");

      // execute the update
      stmt = conn.prepareStatement("UPDATE ndx_files SET mtime = ? WHERE ndxid = ? AND name = ?;");
      stmt.setLong(1,mtime);
      stmt.setInt(2,ndx);
      stmt.setString(3,file);
      stmt.executeUpdate();

    } // end try
    catch (SQLException e)
    { // translate to a general DatabaseException
      throw generalException(e);

    } // end catch
    finally
    { // shut everything down
      MySQLUtils.unlockTables(conn);
      SQLUtils.shutdown(stmt);
      SQLUtils.shutdown(stmt2);
      SQLUtils.shutdown(conn);

    } // end finally

  } // end setModTime

  void deleteFile(int ndx, String file) throws DatabaseException
  {
    Connection conn = null;
    PreparedStatement stmt = null;
    Statement stmt2 = null;
    try
    { // get a connection
      conn = getConnection();

      // lock the table
      stmt2 = conn.createStatement();
      stmt2.executeUpdate("LOCK TABLES ndx_files WRITE;");

      // create and execute the statement
      stmt = conn.prepareStatement("DELETE FROM ndx_files WHERE ndxid = ? AND name = ?;");
      stmt.setInt(1,ndx);
      stmt.setString(2,file);
      stmt.executeUpdate();

    } // end try
    catch (SQLException e)
    { // translate to a general DatabaseException
      throw generalException(e);

    } // end catch
    finally
    { // shut everything down
      MySQLUtils.unlockTables(conn);
      SQLUtils.shutdown(stmt);
      SQLUtils.shutdown(stmt2);
      SQLUtils.shutdown(conn);

    } // end finally

  } // end deleteFile

  void renameFile(int ndx, String oldfile, String newfile) throws DatabaseException
  {
    Connection conn = null;
    PreparedStatement stmt = null;
    Statement stmt2 = null;
    ResultSet rs = null;
    try
    { // get a connection
      conn = getConnection();

      // lock the table
      stmt2 = conn.createStatement();
      stmt2.executeUpdate("LOCK TABLES ndx_files WRITE;");

      // see if the "newfile" is present
      stmt = conn.prepareStatement("SELECT mtime FROM ndx_files WHERE ndxid = ? AND name = ?;");
      stmt.setInt(1,ndx);
      stmt.setString(2,newfile);
      rs = stmt.executeQuery();
      boolean exists = rs.next();
      rs.close();
      rs = null;
      stmt.close();

      if (exists)
      { // delete the existing "newfile"
	stmt = conn.prepareStatement("DELETE FROM ndx_files WHERE ndxid = ? AND name = ?;");
	stmt.setInt(1,ndx);
	stmt.setString(2,newfile);
	stmt.executeUpdate();
	stmt.close();

      } // end if

      // rename the old file to the new filename
      stmt = conn.prepareStatement("UPDATE ndx_files SET name = ? WHERE ndxid = ? AND name = ?;");
      stmt.setString(1,newfile);
      stmt.setInt(2,ndx);
      stmt.setString(3,oldfile);
      stmt.executeUpdate();

    } // end try
    catch (SQLException e)
    { // translate to a general DatabaseException
      throw generalException(e);

    } // end catch
    finally
    { // shut everything down
      MySQLUtils.unlockTables(conn);
      SQLUtils.shutdown(rs);
      SQLUtils.shutdown(stmt);
      SQLUtils.shutdown(stmt2);
      SQLUtils.shutdown(conn);

    } // end finally

  } // end renameFile

  int getLength(int ndx, String file) throws DatabaseException
  {
    Connection conn = null;
    PreparedStatement stmt = null;
    ResultSet rs = null;
    try
    { // get a connection
      conn = getConnection();

      // create and execute the statement
      stmt = conn.prepareStatement("SELECT length FROM ndx_files WHERE ndxid = ? AND name = ?;");
      stmt.setInt(1,ndx);
      stmt.setString(2,file);
      rs = stmt.executeQuery();
      if (rs.next())
	return rs.getInt(1);
      else
	return -1;

    } // end try
    catch (SQLException e)
    { // translate to a general DatabaseException
      throw generalException(e);

    } // end catch
    finally
    { // shut everything down
      SQLUtils.shutdown(rs);
      SQLUtils.shutdown(stmt);
      SQLUtils.shutdown(conn);

    } // end finally

  } // end getLength

  long createNewEntry(int ndx, String file) throws DatabaseException
  {
    Connection conn = null;
    PreparedStatement stmt = null;
    Statement stmt2 = null;
    ResultSet rs = null;
    try
    { // get a connection
      conn = getConnection();

      // lock the table
      stmt2 = conn.createStatement();
      stmt2.executeUpdate("LOCK TABLES ndx_files WRITE;");

      // see if the entry exists already
      stmt = conn.prepareStatement("SELECT mtime FROM ndx_files WHERE ndxid = ? AND name = ?;");
      stmt.setInt(1,ndx);
      stmt.setString(2,file);
      rs = stmt.executeQuery();
      if (rs.next())
	return -1L;

      rs.close();
      rs = null;
      stmt.close();

      // insert the new row
      stmt = conn.prepareStatement("INSERT INTO ndx_files (ndxid, name, mtime) VALUES (?, ?, ?);");
      stmt.setInt(1,ndx);
      stmt.setString(2,file);
      long rc = System.currentTimeMillis();
      stmt.setLong(3,rc);
      stmt.executeUpdate();
      return rc;

    } // end try
    catch (SQLException e)
    { // translate to a general DatabaseException
      throw generalException(e);

    } // end catch
    finally
    { // shut everything down
      MySQLUtils.unlockTables(conn);
      SQLUtils.shutdown(rs);
      SQLUtils.shutdown(stmt);
      SQLUtils.shutdown(stmt2);
      SQLUtils.shutdown(conn);

    } // end finally

  } // end createNewEntry

  long loadFile(int ndx, String file, File output) throws DatabaseException, IOException
  {
    Connection conn = null;
    PreparedStatement stmt = null;
    ResultSet rs = null;
    try
    { // get a connection
      conn = getConnection();

      // get the modification time and data stream
      stmt = conn.prepareStatement("SELECT mtime, data FROM ndx_files WHERE ndxid = ? AND name = ?;");
      stmt.setInt(1,ndx);
      stmt.setString(2,file);
      rs = stmt.executeQuery();
      if (!(rs.next()))
	return -1L;

      long rc = rs.getLong(1);  // get the mod time

      // Copy the file data to the output file.
      FileOutputStream fstm = new FileOutputStream(output);
      IOUtils.copy(rs.getBinaryStream(2),fstm);
      fstm.close();

      return rc;
      
    } // end try
    catch (SQLException e)
    { // translate to a general DatabaseException
      throw generalException(e);

    } // end catch
    finally
    { // shut everything down
      SQLUtils.shutdown(rs);
      SQLUtils.shutdown(stmt);
      SQLUtils.shutdown(conn);

    } // end finally

  } // end loadFile

  void storeFile(int ndx, String file, long mtime, File input) throws DatabaseException, IOException
  {
    Connection conn = null;
    PreparedStatement stmt = null;
    Statement stmt2 = null;
    ResultSet rs = null;
    try
    { // get a connection
      conn = getConnection();

      // lock the table
      stmt2 = conn.createStatement();
      stmt2.executeUpdate("LOCK TABLES ndx_files WRITE;");

      // create and execute the statement
      stmt = conn.prepareStatement("UPDATE ndx_files SET length = ?, mtime = ?, data = ? WHERE ndxid = ? "
				   + "AND name = ?;");
      int len = (int)(input.length());
      stmt.setInt(1,len);
      stmt.setLong(2,mtime);
      stmt.setBinaryStream(3,new FileInputStream(input),len);
      stmt.setInt(4,ndx);
      stmt.setString(5,file);
      stmt.executeUpdate();

    } // end try
    catch (SQLException e)
    { // translate to a general DatabaseException
      throw generalException(e);

    } // end catch
    finally
    { // shut everything down
      SQLUtils.shutdown(rs);
      SQLUtils.shutdown(stmt);
      SQLUtils.shutdown(conn);

    } // end finally

  } // end storeFile

  boolean obtainLock(int ndx, String lock) throws DatabaseException
  {
    Connection conn = null;
    PreparedStatement stmt = null;
    Statement stmt2 = null;
    ResultSet rs = null;
    try
    { // get a connection
      conn = getConnection();

      // lock the table
      stmt2 = conn.createStatement();
      stmt2.executeUpdate("LOCK TABLES ndx_locks WRITE;");

      // see if the lock is already present
      stmt = conn.prepareStatement("SELECT ndxid FROM ndx_locks WHERE ndxid = ? AND name = ?;");
      stmt.setInt(1,ndx);
      stmt.setString(2,lock);
      rs = stmt.executeQuery();
      if (rs.next())
	return false;  // lock already present
      rs.close();
      rs = null;
      stmt.close();

      // insert the lock and return success
      stmt = conn.prepareStatement("INSERT INTO ndx_locks (ndxid, name) VALUES (?, ?);");
      stmt.setInt(1,ndx);
      stmt.setString(2,lock);
      stmt.executeUpdate();
      return true;

    } // end try
    catch (SQLException e)
    { // translate to a general DatabaseException
      throw generalException(e);

    } // end catch
    finally
    { // shut everything down
      MySQLUtils.unlockTables(conn);
      SQLUtils.shutdown(rs);
      SQLUtils.shutdown(stmt);
      SQLUtils.shutdown(stmt2);
      SQLUtils.shutdown(conn);

    } // end finally

  } // end obtain lock

  void releaseLock(int ndx, String lock) throws DatabaseException
  {
    Connection conn = null;
    PreparedStatement stmt = null;
    Statement stmt2 = null;
    try
    { // get a connection
      conn = getConnection();

      // lock the table
      stmt2 = conn.createStatement();
      stmt2.executeUpdate("LOCK TABLES ndx_locks WRITE;");

      // remove the lock row
      stmt = conn.prepareStatement("DELETE FROM ndx_locks WHERE ndxid = ? AND name = ?;");
      stmt.setInt(1,ndx);
      stmt.setString(2,lock);
      stmt.executeUpdate();

    } // end try
    catch (SQLException e)
    { // translate to a general DatabaseException
      throw generalException(e);

    } // end catch
    finally
    { // shut everything down
      MySQLUtils.unlockTables(conn);
      SQLUtils.shutdown(stmt);
      SQLUtils.shutdown(stmt2);
      SQLUtils.shutdown(conn);

    } // end finally

  } // end releaseLock

  void releaseAllLocks(int ndx) throws DatabaseException
  {
    Connection conn = null;
    PreparedStatement stmt = null;
    Statement stmt2 = null;
    try
    { // get a connection
      conn = getConnection();

      // lock the table
      stmt2 = conn.createStatement();
      stmt2.executeUpdate("LOCK TABLES ndx_locks WRITE;");

      // remove the lock row
      stmt = conn.prepareStatement("DELETE FROM ndx_locks WHERE ndxid = ?;");
      stmt.setInt(1,ndx);
      stmt.executeUpdate();

    } // end try
    catch (SQLException e)
    { // translate to a general DatabaseException
      throw generalException(e);

    } // end catch
    finally
    { // shut everything down
      MySQLUtils.unlockTables(conn);
      SQLUtils.shutdown(stmt);
      SQLUtils.shutdown(stmt2);
      SQLUtils.shutdown(conn);

    } // end finally

  } // end releaseAllLocks

} // end class IndexOps_mysql
