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

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

public class AdvancedUserOps_mysql extends AdvancedUserOps
{
  /*--------------------------------------------------------------------------------
   * Attributes
   *--------------------------------------------------------------------------------
   */

  private DBUtilities m_utils;

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

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

  } // end constructor

  /*--------------------------------------------------------------------------------
   * Internal operations
   *--------------------------------------------------------------------------------
   */

  private final String preparePropertySearchTerm(SearchMode mode, String term)
  {
    StringBuffer buf = new StringBuffer();
    if (SearchMode.PREFIX.equals(mode))
      buf.append("LIKE '!").append(m_utils.encodeStringWildcards(term)).append("%'");
    else if (SearchMode.SUBSTRING.equals(mode))
      buf.append("LIKE '!%").append(m_utils.encodeStringWildcards(term)).append("%'");
    else if (SearchMode.REGEXP.equals(mode))
    { // for regular expressions, if we're matching the start of the string, we have to include the ! prefix
      buf.append("REGEXP '");
      if (term.startsWith("^"))
	buf.append("^!").append(m_utils.encodeString(term.substring(1)));
      else
	buf.append(m_utils.encodeString(term));
      buf.append('\'');

    } // end else if

    return buf.toString();

  } // end preparePropertySearchTerm

  /*--------------------------------------------------------------------------------
   * Overrides from class OpsBase
   *--------------------------------------------------------------------------------
   */

  public void dispose()
  {
    m_utils = null;
    super.dispose();

  } // end dispose

  /*--------------------------------------------------------------------------------
   * Abstract implementations from class AdvancedUserOps
   *--------------------------------------------------------------------------------
   */

  int[] searchProperty(int nsid, String name, SearchMode mode, String term, int offset, int count)
      throws DatabaseException
  {
    Connection conn = null;
    Statement stmt = null;
    ResultSet rs = null;
    try
    { // get a connection
      conn = getConnection();

      // prepare and execute a query (note that we assemble it in SQL form)
      StringBuffer sql = new StringBuffer("SELECT u.uid FROM users u, userprop p WHERE u.uid = p.uid "
					  + "AND u.is_anon = 0 AND p.nsid = ");
      sql.append(nsid).append(" AND p.prop_name = '").append(m_utils.encodeString(name)).append("' AND p.prop_value ");
      sql.append(preparePropertySearchTerm(mode,term));
      sql.append(" ORDER BY u.name LIMIT ").append(offset).append(", ").append(count+1).append(';');
      stmt = conn.createStatement();
      rs = stmt.executeQuery(sql.toString());

      // We *know* the maximum number of indexes that can be returned, so allocate a temporary array big
      // enough to hold them all.
      int[] tmp = new int[count+1];
      int ct = 0;
      while (rs.next())
	tmp[ct++] = rs.getInt(1);

      // Create the actual return array and fill it.
      int[] rc = new int[ct];
      System.arraycopy(tmp,0,rc,0,ct);
      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 searchProperty

  int searchPropertyCount(int nsid, String name, SearchMode mode, String term) throws DatabaseException
  {
    Connection conn = null;
    Statement stmt = null;
    ResultSet rs = null;
    try
    { // get a connection
      conn = getConnection();

      // prepare and execute a query (note that we assemble it in SQL form)
      StringBuffer sql = new StringBuffer("SELECT COUNT(*) FROM users u, userprop p WHERE u.uid = p.uid "
					  + "AND u.is_anon = 0 AND p.nsid = ");
      sql.append(nsid).append(" AND p.prop_name = '").append(m_utils.encodeString(name)).append("' AND p.prop_value ");
      sql.append(preparePropertySearchTerm(mode,term));
      sql.append(';');
      stmt = conn.createStatement();
      rs = stmt.executeQuery(sql.toString());
      return SQLUtils.getReturnCountInt(rs,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 searchPropertyCount

  int[] searchName(SearchMode mode, String term, int offset, int count) throws DatabaseException
  {
    Connection conn = null;
    Statement stmt = null;
    ResultSet rs = null;
    try
    { // get a connection
      conn = getConnection();

      // prepare and execute a query (note that we assemble it in SQL form)
      StringBuffer sql = new StringBuffer("SELECT uid FROM users WHERE is_anon = 0 AND username ");
      if (SearchMode.PREFIX.equals(mode))
	sql.append("LIKE '").append(m_utils.encodeStringWildcards(term)).append("%'");
      else if (SearchMode.SUBSTRING.equals(mode))
	sql.append("LIKE '%").append(m_utils.encodeStringWildcards(term)).append("%'");
      else if (SearchMode.REGEXP.equals(mode))
	sql.append("REGEXP '").append(m_utils.encodeString(term)).append('\'');
      sql.append(" ORDER BY username LIMIT ").append(offset).append(", ").append(count+1).append(';');
      stmt = conn.createStatement();
      rs = stmt.executeQuery(sql.toString());

      // We *know* the maximum number of indexes that can be returned, so allocate a temporary array big
      // enough to hold them all.
      int[] tmp = new int[count+1];
      int ct = 0;
      while (rs.next())
	tmp[ct++] = rs.getInt(1);

      // Create the actual return array and fill it.
      int[] rc = new int[ct];
      System.arraycopy(tmp,0,rc,0,ct);
      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 searchName

  int searchNameCount(SearchMode mode, String term) throws DatabaseException
  {
    Connection conn = null;
    Statement stmt = null;
    ResultSet rs = null;
    try
    { // get a connection
      conn = getConnection();

      // prepare and execute a query (note that we assemble it in SQL form)
      StringBuffer sql = new StringBuffer("SELECT COUNT(*) FROM users WHERE is_anon = 0 AND username ");
      if (SearchMode.PREFIX.equals(mode))
	sql.append("LIKE '").append(m_utils.encodeStringWildcards(term)).append("%'");
      else if (SearchMode.SUBSTRING.equals(mode))
	sql.append("LIKE '%").append(m_utils.encodeStringWildcards(term)).append("%'");
      else if (SearchMode.REGEXP.equals(mode))
	sql.append("REGEXP '").append(m_utils.encodeString(term)).append('\'');
      sql.append(';');
      stmt = conn.createStatement();
      rs = stmt.executeQuery(sql.toString());
      return SQLUtils.getReturnCountInt(rs,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 searchNameCount

} // end class AdvancedUserOps_mysql
