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

import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
import org.apache.log4j.*;
import com.silverwrist.util.StringUtil;
import com.silverwrist.venice.core.*;
import com.silverwrist.venice.except.*;
import com.silverwrist.venice.servlets.format.*;

public class PostMessage extends VeniceServlet
{
  /*--------------------------------------------------------------------------------
   * Static data members
   *--------------------------------------------------------------------------------
   */

  private static Category logger = Category.getInstance(PostMessage.class.getName());

  /*--------------------------------------------------------------------------------
   * Internal functions
   *--------------------------------------------------------------------------------
   */

  private static int getPostNumber(ServletRequest request, String on_error) throws ErrorBox
  {
    String str = request.getParameter("sd");
    if (StringUtil.isStringEmpty(str))
      throw new ErrorBox(null,"Invalid parameter.",on_error);
    try
    { // get the number of posts we think he topic has
      return Integer.parseInt(str);

    } // end try
    catch (NumberFormatException nfe)
    { // not a good integer...
      throw new ErrorBox(null,"Invalid parameter.",on_error);

    } // end catch

  } // end getPostNumber

  /*--------------------------------------------------------------------------------
   * Overrides from class HttpServlet
   *--------------------------------------------------------------------------------
   */

  public String getServletInfo()
  {
    String rc = "PostMessage servlet - Handles posting messages to a conference\n"
              + "Part of the Venice Web Communities System\n";
    return rc;

  } // end getServletInfo

  /*--------------------------------------------------------------------------------
   * Overrides from class VeniceServlet
   *--------------------------------------------------------------------------------
   */

  protected VeniceContent doVenicePost(HttpServletRequest request, VeniceEngine engine,
				       UserContext user, RenderData rdat)
    throws ServletException, IOException, VeniceServletResult
  {
    // get the community
    CommunityContext comm = getCommunityParameter(request,user,true,"top");
    changeMenuCommunity(request,comm);

    // get the conference
    ConferenceContext conf = getConferenceParameter(request,comm,true,"top");

    // get the topic
    TopicContext topic = getTopicParameter(request,conf,true,"top");

    String on_error = "confdisp?sig=" + comm.getCommunityID() + "&conf=" + conf.getConfID() + "&top="
                    + topic.getTopicNumber();

    if (isImageButtonClicked(request,"cancel"))
      throw new RedirectResult(on_error);  // canceled posting - take us back

    // make sure we've got some post data
    String raw_postdata = request.getParameter("pb");
    /* EJB 4/4/2001 - take this code out, FUTURE: maybe make it a global setting?
    if (StringUtil.isStringEmpty(raw_postdata))
      return null;  // don't allow zero-size posts
    -- end removed code */

    if (raw_postdata==null)
      raw_postdata = "";

    final String yes = "Y";

    if (isImageButtonClicked(request,"preview"))  // generate a preview
      return new PostPreview(engine,comm,conf,topic,request.getParameter("pseud"),raw_postdata,
			     request.getParameter("next"),getPostNumber(request,on_error),
			     yes.equals(request.getParameter("attach")),
			     yes.equals(request.getParameter("slip")));

    if (   isImageButtonClicked(request,"post") || isImageButtonClicked(request,"postnext")
	|| isImageButtonClicked(request,"posttopics"))
    { // post the message, and then either go back to the same topic or on to the next one
      boolean go_next = isImageButtonClicked(request,"postnext");
      boolean go_topics = isImageButtonClicked(request,"posttopics");
      int pn = getPostNumber(request,on_error);

      try
      { // first check for slippage
	if (pn!=topic.getTotalMessages()) // slippage detected!  display the slippage screen
	  return new PostSlippage(engine,comm,conf,topic,pn,request.getParameter("next"),
				  request.getParameter("pseud"),raw_postdata,
				  yes.equals(request.getParameter("attach")));

	// post the darn thing!
	TopicMessageContext msg = topic.postNewMessage(0,request.getParameter("pseud"),raw_postdata);

	if (!(yes.equals(request.getParameter("slip"))))
	  topic.fixSeen();  // no slippage = make sure we mark all as read

	// where do we want to go now?
	String target;
	if (go_topics)
	  target = "confdisp?sig=" + comm.getCommunityID() + "&conf=" + conf.getConfID();
	else
	{ // figure out what topic to go to next
	  short next;
	  try
	  { // attempt to get the value of the "next topic" parameter
	    if (go_next)
	    { // get the "next topic" parameter
	      String foo = request.getParameter("next");
	      if (StringUtil.isStringEmpty(foo))
		next = topic.getTopicNumber();
	      else
		next = Short.parseShort(foo);

	    } // end if
	    else
	      next = topic.getTopicNumber();

	  } // end try
	  catch (NumberFormatException nfe)
	  { // just default me
	    next = topic.getTopicNumber();

	  } // end catch

	  target = "confdisp?sig=" + comm.getCommunityID() + "&conf=" + conf.getConfID() + "&top="
	         + next + "&rnm=1";

	} // end else

	if (yes.equals(request.getParameter("attach")))
	  return new AttachmentForm(comm,conf,msg,target);  // go to upload an attachment

	// no attachment - redirect where we need to go
	throw new RedirectResult(target);

      } // end try
      catch (DataException de)
      { // there was a database error posting the message
	return new ErrorBox("Database Error","Database error posting message: " + de.getMessage(),"top");

      } // end catch
      catch (AccessError ae)
      { // we were unable to post the message
	return new ErrorBox("Access Error",ae.getMessage(),"top");

      } // end catch

    } // end if

    // unknown button clicked
    logger.error("no known button click on PostMessage.doPost");
    return new ErrorBox("Internal Error","Unknown command button pressed","top");

  } // end doVenicePost

} // end class PostMessage
