/*
 * 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) 2001-02 Eric J. Bowersox/Silverwrist Design Studios.  All Rights Reserved.
 * 
 * Contributor(s): 
 */
package com.silverwrist.venice.core.impl;

import java.sql.*;
import org.apache.log4j.*;
import com.silverwrist.venice.db.*;
import com.silverwrist.venice.except.InternalStateError;
import com.silverwrist.venice.core.internals.*;
import com.silverwrist.venice.svc.*;

class BackgroundConferencePurge implements Runnable
{
  /*--------------------------------------------------------------------------------
   * Static data members
   *--------------------------------------------------------------------------------
   */

  private static Category logger = Category.getInstance(BackgroundConferencePurge.class);

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

  private GlobalSite globalsite;         // the global site
  private EnvEngine env;                 // the environment
  private int confid;                    // the conference ID
  private int num_topics;                // the number of topics
  private int max_topicid;               // the maximum topic ID

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

  BackgroundConferencePurge(GlobalSite globalsite, EnvEngine env, int confid, int num_topics, int max_topicid)
  {
    this.globalsite = globalsite;
    this.env = env;
    this.confid = confid;
    this.num_topics = num_topics;
    this.max_topicid = max_topicid;

  } // end constructor

  /*--------------------------------------------------------------------------------
   * Implementations from interface Runnable
   *--------------------------------------------------------------------------------
   */

  public void run()
  {
    if (logger.isDebugEnabled())
      logger.debug("BackgroundConferencePurge running on conference #" + confid);

    Connection conn = null;  // pooled database connection
    Statement stmt = null;

    try
    { // get a database connection from the pool
      conn = globalsite.getConnection(null);
      stmt = conn.createStatement();

      // purge out some auxiliary tables first
      stmt.executeUpdate("DELETE FROM confmember WHERE confid = " + confid + ";");
      stmt.executeUpdate("DELETE FROM confsettings WHERE confid = " + confid + ";");
      stmt.executeUpdate("DELETE FROM confhotlist WHERE confid = " + confid + ";");
      stmt.executeUpdate("DELETE FROM propconf WHERE confid = " + confid + ";");
      stmt.executeUpdate("DELETE FROM confcustom WHERE confid = " + confid + ";");

      // look up all the topic IDs that are present in this conference
      int[] topicids = new int[num_topics];
      StringBuffer sql = new StringBuffer("SELECT topicid FROM topics WHERE confid = ");
      sql.append(confid).append(" AND topicid <= ").append(max_topicid).append(" ORDER BY topicid;");
      ResultSet rs = stmt.executeQuery(sql.toString());
      int topics = 0;
      while (rs.next())
	topicids[topics++] = rs.getInt(1);
      SQLUtil.shutdown(rs);

      for (int i=0; i<topics; i++)
      { // delete the topic header and settings rows first
	stmt.executeUpdate("DELETE FROM topics WHERE topicid = " + topicids[i] + ";");
	stmt.executeUpdate("DELETE FROM topicsettings WHERE topicid = " + topicids[i] + ";");
	stmt.executeUpdate("DELETE FROM topicbozo WHERE topicid = " + topicids[i] + ";");

	// figure out how many posts are in this topic and create a BackgroundTopicPurge.
	sql.setLength(0);
	sql.append("SELECT COUNT(*), MAX(postid) FROM posts WHERE topicid = ").append(topicids[i]).append(';');
	rs = stmt.executeQuery(sql.toString());
	if (!(rs.next()))
	  throw new InternalStateError("BackgroundConferencePurge.run screwup on post SELECT");
	globalsite.queueTask(new BackgroundTopicPurge(globalsite,env,topicids[i],rs.getInt(1),rs.getLong(2)),
			     GlobalSite.TASK_PRIO_NORMAL-1);
	SQLUtil.shutdown(rs);

      } // end for

      if (logger.isDebugEnabled())
	logger.debug("BackgroundConferencePurge basic delete complete for conf #" + confid);

    } // end try
    catch (SQLException e)
    { // on an error, just die
      logger.error("BackgroundConferencePurge FATAL EXCEPTION purging #" + confid + ": " + e.getMessage(),e);
      return;

    } // end catch
    finally
    { // make sure we release the connection before we go
      SQLUtil.shutdown(stmt);
      SQLUtil.shutdown(conn);

    } // end finally

    if (logger.isDebugEnabled())
      logger.debug("BackgroundConferencePurge COMPLETE for conf #" + confid);

  } // end run

} // end class BackgroundConferencePurge
