/*
 * 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.security;

import java.security.Principal;
import java.security.acl.AclNotFoundException;
import java.sql.*;
import java.util.*;
import com.silverwrist.util.*;
import com.silverwrist.dynamo.except.*;
import com.silverwrist.dynamo.iface.*;

public class SRMOperations_mysql extends SRMOperations
{
  /*--------------------------------------------------------------------------------
   * Static data members
   *--------------------------------------------------------------------------------
   */

  private static final int PRINCIPALFLAG_USER = 0;
  private static final int PRINCIPALFLAG_GROUP = 1;

  private static final int ACEFLAG_POSITIVE = 0;
  private static final int ACEFLAG_NEGATIVE = 16;

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

  private DBUtilities m_utils;                // reference to utilities object
  private AclOperations m_acl_ops = null;     // ACL operations object
  private AceOperations m_ace_ops = null;     // ACE operations object

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

  public SRMOperations_mysql(DBConnectionPool pool)
  {
    super(pool);
    m_utils = (DBUtilities)(pool.queryService(DBUtilities.class));

  } // end constructor

  /*--------------------------------------------------------------------------------
   * Abstract implementations from class SRMOperations
   *--------------------------------------------------------------------------------
   */

  synchronized AclOperations getAclOperations()
  {
    if (m_acl_ops==null)
      m_acl_ops = new AclOperations_mysql(getPool(),m_utils);
    return m_acl_ops;

  } // end getAclOperations

  synchronized AceOperations getAceOperations()
  {
    if (m_ace_ops==null)
      m_ace_ops = new AceOperations_mysql(getPool(),m_utils);
    return m_ace_ops;

  } // end getAceOperations

  Map getAclData(int aclid) throws DatabaseException, AclNotFoundException
  {
    Connection conn = null;
    PreparedStatement stmt = null;
    ResultSet rs = null;
    try
    { // get a connection
      conn = getConnection();

      // get the ACL name
      stmt = conn.prepareStatement("SELECT aclname FROM acl WHERE aclid = ?;");
      stmt.setInt(1,aclid);
      rs = stmt.executeQuery();
      if (!(rs.next()))
	throw new AclNotFoundException();

      // compose the return map
      HashMap map = new HashMap();
      map.put(HMKEY_ACLID,new Integer(aclid));
      map.put(HMKEY_ACLNAME,rs.getString(1));
      return map;

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

  Map createAcl(String name, int owner_id, boolean owner_group) throws DatabaseException
  {
    Connection conn = null;
    PreparedStatement stmt = null;
    Statement stmt2 = null;
    ResultSet rs = null;
    try
    { // get a connection
      conn = getConnection();

      // lock the table while we work
      stmt2 = conn.createStatement();
      stmt2.executeUpdate("LOCK TABLES acl WRITE;");

      // create the insert statement
      stmt = conn.prepareStatement("INSERT INTO acl (aclname) VALUES (?);");
      stmt.setString(1,name);
      stmt.executeUpdate();

      // prepare the return map
      HashMap rc = new HashMap();
      rc.put(HMKEY_ACLID,new Integer(MySQLUtils.getLastInsertInt(conn)));
      rc.put(HMKEY_ACLNAME,name);
      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 createAcl

  Map getAceData(int aceid) throws DatabaseException
  {
    Connection conn = null;
    PreparedStatement stmt = null;
    ResultSet rs = null;
    try
    { // get a connection
      conn = getConnection();

      // get the ACE data
      stmt = conn.prepareStatement("SELECT pri, flags FROM ace WHERE aceid = ?;");
      stmt.setInt(1,aceid);
      rs = stmt.executeQuery();
      if (!(rs.next()))
      { // throw DatabaseException if the ACE isn't there
	DatabaseException de = new DatabaseException(SRMOperations_mysql.class,"SecurityMessages",
						     "ace.notFound");
	de.setParameter(0,String.valueOf(aceid));
	throw de;

      } // end if

      // Get the output data and create the return HashMap.
      int pr_id = rs.getInt(1);
      boolean no_principal = rs.wasNull();
      int flags = rs.getInt(2);
      HashMap rc = new HashMap();
      rc.put(HMKEY_ACEID,new Integer(aceid));
      if (!no_principal)
	rc.put(HMKEY_PRINCIPAL,new PrincipalID(pr_id,((flags & PRINCIPALFLAG_GROUP)!=0)));
      rc.put(HMKEY_NEGATIVE,Boolean.valueOf((flags & ACEFLAG_NEGATIVE)!=0));
      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 getAceData

  int createAce() throws DatabaseException
  {
    Connection conn = null;
    Statement stmt = null;
    try
    { // get a connection
      conn = getConnection();

      // lock table while we work
      stmt = conn.createStatement();
      stmt.executeUpdate("LOCK TABLES ace WRITE;");

      // insert a new ACE entry
      SQLUtils.shutdown(stmt);
      stmt.executeUpdate("INSERT INTO ace (flags) VALUES (0);");
      return MySQLUtils.getLastInsertInt(conn);

    } // 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(conn);

    } // end finally

  } // end createAce

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

      // get the data from the table
      stmt = conn.createStatement();
      rs = stmt.executeQuery("SELECT admin_uid, admin_gid, global_aclid, alluser_gid, verified_gid "
			     + "FROM globalsec;");
      if (!(rs.next()))
	throw new DatabaseException(SRMOperations_mysql.class,"SecurityMessages","globalData.notPresent");

      // return it as an array
      int[] rc = new int[5];
      rc[NDX_ADMIN_UID] = rs.getInt(1);
      rc[NDX_ADMIN_GID] = rs.getInt(2);
      rc[NDX_GLOBAL_ACLID] = rs.getInt(3);
      rc[NDX_ALL_GID] = rs.getInt(4);
      rc[NDX_VERIFIED_GID] = rs.getInt(5);
      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 getGlobalSecurityData

} // end class SRMOperations_mysql
