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

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 CategoryOps_mysql extends CategoryOps
{
  /*--------------------------------------------------------------------------------
   * Attributes
   *--------------------------------------------------------------------------------
   */

  private DBUtilities m_utils;

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

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

  } // end constructor

  /*--------------------------------------------------------------------------------
   * Abstract implementations from class CategoryOps
   *--------------------------------------------------------------------------------
   */

  boolean verifyCategoryID(int catid) throws DatabaseException
  {
    Connection conn = null;
    PreparedStatement stmt = null;
    ResultSet rs = null;
    try
    { // get a connection
      conn = getConnection();

      // prepare and execute the statement
      stmt = conn.prepareStatement("SELECT catid FROM refcategory WHERE catid = ? AND dontuse = 0;");
      stmt.setInt(1,catid);
      rs = stmt.executeQuery();
      return rs.next();

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

  List getCategoriesList(int parent) 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 catid, symlink, name FROM refcategory WHERE parent = ? AND dontuse = 0 "
                                   + "ORDER BY name;");
      stmt.setInt(1,parent);
      rs = stmt.executeQuery();

      // create the return list of CategoryTuple values
      ArrayList rc = new ArrayList();
      while (rs.next())
	rc.add(new CategoryTuple(rs.getInt(1),parent,rs.getInt(2),rs.getString(3)));
      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 getCategoriesList

  CategoryTuple getCategory(int catid) 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 parent, symlink, name FROM refcategory WHERE catid = ? AND dontuse = 0;");
      stmt.setInt(1,catid);
      rs = stmt.executeQuery();

      if (rs.next())
	return new CategoryTuple(catid,rs.getInt(1),rs.getInt(2),rs.getString(3));
      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 getCategory

  List search(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();

      // build the SQL statement as a string
      StringBuffer sql = new StringBuffer("SELECT catid, parent, symlink, name FROM refcategory WHERE name ");
      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(" AND dontuse = 0 ORDER BY parent, name LIMIT ").append(offset).append(", ").append(count+1);
      sql.append(';');

      // execute the operation!
      stmt = conn.createStatement();
      rs = stmt.executeQuery(sql.toString());

      // create the return list of CategoryTuple values
      ArrayList rc = new ArrayList(count+1);
      while (rs.next())
	rc.add(new CategoryTuple(rs.getInt(1),rs.getInt(2),rs.getInt(3),rs.getString(4)));
      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 searchForCategories

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

      // build the SQL statement as a string
      StringBuffer sql = new StringBuffer("SELECT COUNT(*) FROM refcategory WHERE name ");
      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(" AND dontuse = 0;");

      // execute the operation!
      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 getSearchCount

} // end class CategoryOps_mysql
