/*
 * 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) 2002 Eric J. Bowersox/Silverwrist Design Studios.  All Rights Reserved.
 * 
 * Contributor(s): 
 */
package com.silverwrist.dynamo.db;

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

class UserObjectOps_mysql extends UserObjectOps
{
  /*--------------------------------------------------------------------------------
   * Static data members
   *--------------------------------------------------------------------------------
   */

  private static final String[] STRING_TEMPLATE = new String[0];

  /*--------------------------------------------------------------------------------
   * Attributes
   *--------------------------------------------------------------------------------
   */

  private DBUtilities m_utils;
  private PropertySerializer m_psz;

  /*--------------------------------------------------------------------------------
   * Constructor
   *--------------------------------------------------------------------------------
   */

  UserObjectOps_mysql(DBConnectionPool pool, DBUtilities utils)
  {
    super(pool);
    m_utils = utils;
    m_psz = (PropertySerializer)(pool.queryService(PropertySerializer.class));

  } // end constructor

  /*--------------------------------------------------------------------------------
   * Abstract implementations from class UserObjectOps
   *--------------------------------------------------------------------------------
   */

  Object getProperty(int uid, PropertyKey key) throws DatabaseException
  {
    Connection conn = null;
    PreparedStatement stmt = null;
    ResultSet rs = null;
    String rc_str = null;
    try
    { // get a connection
      conn = getConnection();

      // look up the property
      stmt = conn.prepareStatement("SELECT prop_value FROM userprop WHERE uid = ? AND nsid = ? "
				   + "AND prop_name = ?;");
      stmt.setInt(1,uid);
      stmt.setInt(2,key.getNamespaceID());
      stmt.setString(3,key.getName());
      rs = stmt.executeQuery();
      if (!(rs.next()))
	return null;  // property not found

      rc_str = rs.getString(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

    // Deserialize the property value.
    Object rc = m_psz.deserializeProperty(rc_str);
    if (rc!=null)
      return rc;

    // deserialization exception - throw it
    DatabaseException de = new DatabaseException(UserObjectOps_mysql.class,"DatabaseMessages",
						 "property.deserialize");
    de.setParameter(0,key.getName());
    throw de;

  } // end getProperty

  Object setProperty(int uid, PropertyKey key, Object value) throws DatabaseException
  {
    String serialized_value = m_psz.serializeProperty(value);
    if (serialized_value==null)
    { // serialization exception - throw it
      DatabaseException de = new DatabaseException(UserObjectOps_mysql.class,"DatabaseMessages",
						   "property.serialize");
      de.setParameter(0,key.getName());
      throw de;

    } // end if

    String old_value = null;
    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 userprop WRITE;");

      // look to see if the property value is already there
      stmt = conn.prepareStatement("SELECT prop_value FROM userprop WHERE uid = ? AND nsid = ? "
				   + "AND prop_name = ?;");
      stmt.setInt(1,uid);
      stmt.setInt(2,key.getNamespaceID());
      stmt.setString(3,key.getName());
      rs = stmt.executeQuery();
      if (rs.next())
	old_value = rs.getString(1);
      SQLUtils.shutdown(rs);
      rs = null;
      SQLUtils.shutdown(stmt);

      if (old_value!=null)
      { // prepare the statement to update the existing record
	stmt = conn.prepareStatement("UPDATE userprop SET prop_value = ? WHERE uid = ? "
				     + "AND nsid = ? AND prop_name = ?;");
	stmt.setString(1,serialized_value);
	stmt.setInt(2,uid);
	stmt.setInt(3,key.getNamespaceID());
	stmt.setString(4,key.getName());

      } // end if
      else
      { // prepare the statement to insert a new record
	stmt = conn.prepareStatement("INSERT INTO userprop (uid, nsid, prop_name, prop_value) "
				     + "VALUES (?, ?, ?, ?);");
	stmt.setInt(1,uid);
	stmt.setInt(2,key.getNamespaceID());
	stmt.setString(3,key.getName());
	stmt.setString(4,serialized_value);

      } // end else

      stmt.executeUpdate();  // execute it!

    } // 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

    if (old_value==null)
      return null;  // no previous value

    // Deserialize the property value.
    Object rc = m_psz.deserializeProperty(old_value);
    if (rc!=null)
      return rc;

    // deserialization exception - throw it
    DatabaseException de = new DatabaseException(UserObjectOps_mysql.class,"DatabaseMessages",
						 "property.deserialize");
    de.setParameter(0,key.getName());
    throw de;

  } // end setProperty

  Object removeProperty(int uid, PropertyKey key) throws DatabaseException
  {
    String old_value = null;
    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 userprop WRITE;");

      // look to see if the property value is already there
      stmt = conn.prepareStatement("SELECT prop_value FROM userprop WHERE uid = ? AND nsid = ? "
				   + "AND prop_name = ?;");
      stmt.setInt(1,uid);
      stmt.setInt(2,key.getNamespaceID());
      stmt.setString(3,key.getName());
      rs = stmt.executeQuery();
      if (rs.next())
	old_value = rs.getString(1);
      else
	return null;  // no need to remove anything
      SQLUtils.shutdown(rs);
      rs = null;
      SQLUtils.shutdown(stmt);

      // delete the database row
      stmt = conn.prepareStatement("DELETE FROM userprop WHERE uid = ? AND nsid = ? AND prop_name = ?;");
      stmt.setInt(1,uid);
      stmt.setInt(2,key.getNamespaceID());
      stmt.setString(3,key.getName());
      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

    // Deserialize the property value.
    Object rc = m_psz.deserializeProperty(old_value);
    if (rc!=null)
      return rc;

    // deserialization exception - throw it
    DatabaseException de = new DatabaseException(UserObjectOps_mysql.class,"DatabaseMessages",
						 "property.deserialize");
    de.setParameter(0,key.getName());
    throw de;

  } // end removeProperty

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

      // execute the query!
      stmt = conn.prepareStatement("SELECT DISTINCT nsid FROM userprop WHERE uid = ?;");
      stmt.setInt(1,uid);
      rs = stmt.executeQuery();

      // read out a list of the namespace IDs
      ArrayList tmp = new ArrayList();
      while (rs.next())
	tmp.add(new Integer(rs.getInt(1)));

      // create and return the array
      int[] rc = new int[tmp.size()];
      for (int i=0; i<tmp.size(); i++)
	rc[i] = ((Integer)(tmp.get(i))).intValue();
      tmp.clear();
      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 getPropertyNamespaceIDs

  Map getAllProperties(int uid, int namespace) throws DatabaseException
  {
    Connection conn = null;
    PreparedStatement stmt = null;
    ResultSet rs = null;
    try
    { // get a connection
      conn = getConnection();

      // execute the query!
      stmt = conn.prepareStatement("SELECT prop_name, prop_value FROM userprop WHERE uid = ? AND nsid = ?;");
      stmt.setInt(1,uid);
      stmt.setInt(2,namespace);
      rs = stmt.executeQuery();

      // prepare the return value
      HashMap rc = new HashMap();
      while (rs.next())
      { // copy data out, deserializing properties as we go
	String key = rs.getString(1);
	Object value = m_psz.deserializeProperty(rs.getString(2));
	if (value==null)
	{ // deserialization exception - throw it
	  DatabaseException de = new DatabaseException(UserObjectOps_mysql.class,"DatabaseMessages",
						       "property.deserialize");
	  de.setParameter(0,key);
	  throw de;

	} // end if

	rc.put(key,value);

      } // end while

      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 getAllProperties

  void setLocked(int uid, boolean locked) throws DatabaseException
  {
    Connection conn = null;
    PreparedStatement stmt = null;
    try
    { // get a connection
      conn = getConnection();

      // run the appropriate SQL update
      stmt = conn.prepareStatement("UPDATE users SET locked = ? WHERE uid = ?;");
      stmt.setInt(1,(locked ? 1 : 0));
      stmt.setInt(2,uid);
      stmt.executeUpdate();

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

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

    } // end finally

  } // end setLocked

  void setNoSpam(int uid, boolean nospam) throws DatabaseException
  {
    Connection conn = null;
    PreparedStatement stmt = null;
    try
    { // get a connection
      conn = getConnection();

      // run the appropriate SQL update
      stmt = conn.prepareStatement("UPDATE users SET nospam = ? WHERE uid = ?;");
      stmt.setInt(1,(nospam ? 1 : 0));
      stmt.setInt(2,uid);
      stmt.executeUpdate();

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

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

    } // end finally

  } // end setNoSpam

  void setEMailAddress(int uid, String addr) throws DatabaseException
  {
    Connection conn = null;
    PreparedStatement stmt = null;
    try
    { // get a connection
      conn = getConnection();

      // run the appropriate SQL update
      stmt = conn.prepareStatement("UPDATE users SET email = ? WHERE uid = ?;");
      stmt.setString(1,addr);
      stmt.setInt(2,uid);
      stmt.executeUpdate();

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

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

    } // end finally

  } // end setEMailAddress

  void setLastAccessed(int uid, java.util.Date date) throws DatabaseException
  {
    Connection conn = null;
    PreparedStatement stmt = null;
    try
    { // get a connection
      conn = getConnection();

      // run the appropriate SQL update
      stmt = conn.prepareStatement("UPDATE users SET last_accessed = ? WHERE uid = ?;");
      m_utils.setDateTime(stmt,1,date);
      stmt.setInt(2,uid);
      stmt.executeUpdate();

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

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

    } // end finally

  } // end setLastAccessed

  String[] getAuthenticationData(int uid, int nsid, String method, String source_data) throws DatabaseException
  {
    Connection conn = null;
    PreparedStatement stmt = null;
    ResultSet rs = null;
    try
    { // get a connection
      conn = getConnection();

      // execute the statement!
      stmt = conn.prepareStatement("SELECT auth_data FROM userauth WHERE uid = ? AND nsid = ? "
				   + "AND method = ? AND source_data = ?;");
      stmt.setInt(1,uid);
      stmt.setInt(2,nsid);
      stmt.setString(3,method);
      stmt.setString(4,source_data);
      rs = stmt.executeQuery();
      if (!(rs.next()))
	return null;

      // Construct the return value.
      ArrayList rc = new ArrayList();
      do
      { // append return value
	rc.add(rs.getString(1));

      } while (rs.next());  // end do

      return (String[])(rc.toArray(STRING_TEMPLATE));

    } // 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 getAuthenticationData

  void putAuthenticationData(int uid, int nsid, String method, String source_data, String auth_data)
      throws DatabaseException
  {
    Connection conn = null;
    PreparedStatement stmt = null;
    Statement stmt2 = null;
    ResultSet rs = null;
    try
    { // get a connection
      conn = getConnection();

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

      // look for an existing record
      stmt = conn.prepareStatement("SELECT uid FROM userauth WHERE uid = ? AND nsid = ? AND method = ? "
				   + "AND source_data = ?;");
      stmt.setInt(1,uid);
      stmt.setInt(2,nsid);
      stmt.setString(3,method);
      stmt.setString(4,source_data);
      rs = stmt.executeQuery();
      boolean present = rs.next();
      SQLUtils.shutdown(rs);
      rs = null;
      SQLUtils.shutdown(stmt);

      if (present)
      { // execute an update statement
	stmt = conn.prepareStatement("UPDATE userauth SET auth_data = ? WHERE uid = ? AND nsid = ? "
				     + "AND method = ? AND source_data = ?;");
	stmt.setString(1,auth_data);
	stmt.setInt(2,uid);
	stmt.setInt(3,nsid);
	stmt.setString(4,method);
	stmt.setString(5,source_data);

      } // end if
      else
      { // execute an insert statement
	stmt = conn.prepareStatement("INSERT INTO userauth (uid, nsid, method, source_data, auth_data) "
				     + "VALUES (?, ?, ?, ?, ?);");
	stmt.setInt(1,uid);
	stmt.setInt(2,nsid);
	stmt.setString(3,method);
	stmt.setString(4,source_data);
	stmt.setString(5,auth_data);

      } // end else

      stmt.executeUpdate();  // run it!

    } // 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 putAuthenticationData

  void clearAuthenticationData(int uid, int nsid, String method, String source_data) throws DatabaseException
  {
    Connection conn = null;
    PreparedStatement stmt = null;
    ResultSet rs = null;
    try
    { // get a connection
      conn = getConnection();

      // prepare and run the statement
      if (source_data==null)
	stmt = conn.prepareStatement("DELETE FROM userauth WHERE uid = ? AND nsid = ? AND method = ?;");
      else
	stmt = conn.prepareStatement("DELETE FROM userauth WHERE uid = ? AND nsid = ? AND method = ? "
				     + "AND source_data = ?;");
      stmt.setInt(1,uid);
      stmt.setInt(2,nsid);
      stmt.setString(3,method);
      if (source_data!=null)
	stmt.setString(4,source_data);
      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 clearAuthenticationData

} // end class UserObjectOps_mysql
