/*
 * 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.ServletMultipartHandler;
import com.silverwrist.util.ServletMultipartException;
import com.silverwrist.venice.core.*;
import com.silverwrist.venice.except.*;
import com.silverwrist.venice.servlets.format.*;

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

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

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

  public String getServletInfo()
  {
    String rc = "Attachment servlet - Handles uploading and downloading attachments\n"
              + "Part of the Venice Web Communities System\n";
    return rc;

  } // end getServletInfo

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

  protected VeniceContent doVeniceGet(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 message we want to use
    TopicMessageContext msg = getMessageParameter(request,conf,true,"top");

    String type, filename;
    int length;
    InputStream data;

    try
    { // retrieve the information about the attachment
      type = msg.getAttachmentType();
      filename = msg.getAttachmentFilename();
      length = msg.getAttachmentLength();
      if (logger.isInfoEnabled())
	logger.info("Uploaded file: " + filename + "(type " + type + ", " + length + " bytes)");
      data = msg.getAttachmentData();

    } // end try
    catch (AccessError ae)
    { // unable to access the data stream
      return new ErrorBox("Access Error",ae.getMessage(),"top");

    } // end catch
    catch (DataException de)
    { // error getting at the data stream from the attachment
      return new ErrorBox("Database Error","Database error retrieving attachment: " + de.getMessage(),"top");

    } // end catch

    // now we want to send that data back to the user!
    throw new SendFileResult(type,filename,length,data);

  } // end doVeniceGet

  protected VeniceContent doVenicePost(HttpServletRequest request, ServletMultipartHandler mphandler,
				       VeniceEngine engine, UserContext user, RenderData rdat)
    throws ServletException, IOException, VeniceServletResult
  {
    logger.debug("Attachment.doVenicePost: entry");

    // Get target URL for the operation
    if (mphandler.isFileParam("target"))
    { // bogus target URL
      logger.error("Internal Error: 'target' should be a normal param");
      return new ErrorBox(null,"Internal Error: 'target' should be a normal param","top");

    } // end if

    String target = mphandler.getValue("target");
    if (logger.isDebugEnabled())
      logger.debug("Target URL: " + target);
    setMyLocation(request,target);

    // also check on file parameter status
    if (!(mphandler.isFileParam("thefile")))
    { // bogus file parameter
      logger.error("Internal Error: 'thefile' should be a file param");
      return new ErrorBox(null,"Internal Error: 'thefile' should be a file param",target);

    } // end if

    // get the community
    CommunityContext comm = getCommunityParameter(mphandler,user,true,"top");
    if (logger.isDebugEnabled())
      logger.debug("community param: #" + comm.getCommunityID());
    changeMenuCommunity(request,comm);

    // get the conference
    ConferenceContext conf = getConferenceParameter(mphandler,comm,true,"top");
    if (logger.isDebugEnabled())
      logger.debug("Conference param: #" + conf.getConfID());

    // get the message we want to use
    TopicMessageContext msg = getMessageParameter(mphandler,conf,true,"top");
    if (logger.isDebugEnabled())
      logger.debug("Message param: #" + msg.getPostID());

    try
    { // attach the data to the message!
      msg.attachData(mphandler.getContentType("thefile"),mphandler.getValue("thefile"),
		     mphandler.getContentSize("thefile"),mphandler.getFileContentStream("thefile"));

    } // end try
    catch (ServletMultipartException smpe)
    { // error processing the file parameter data
      logger.error("Servlet multipart error:",smpe);
      return new ErrorBox(null,"Internal Error: " + smpe.getMessage(),target);

    } // end catch
    catch (AccessError ae)
    { // access error posting the attachment data
      logger.error("Access error:",ae);
      return new ErrorBox("Access Error",ae.getMessage(),target);

    } // end catch
    catch (DataException de)
    { // error storing the attachment in the database
      logger.error("DataException:",de);
      return new ErrorBox("Database Error","Database error storing attachment: " + de.getMessage(),target);

    } // end catch

    logger.debug("Attachment.doVenicePost: done!");
    throw new RedirectResult(target);  // get back, get back, get back to where you once belonged

  } // end doVenicePost

} // end class Attachment
