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

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

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

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

  public String getServletInfo()
  {
    String rc = "CommunityLogo servlet - changes the community logo for a community\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,null);
    changeMenuCommunity(request,comm);
    if (!(comm.canModifyProfile()))
      return new ErrorBox("Community Error","You are not permitted to modify this community's profile.",null);

    try
    { // create the display
      return new CommunityLogoData(engine,comm,rdat);

    } // end try
    catch (DataException de)
    { // error getting at the data stream from the attachment
      return new ErrorBox("Database Error","Database error generating display: " + de.getMessage(),
			  "sigadmin?cmd=P&sig=" + comm.getCommunityID());

    } // end catch

  } // end doVeniceGet

  protected VeniceContent doVenicePost(HttpServletRequest request, ServletMultipartHandler mphandler,
				       VeniceEngine engine, UserContext user, RenderData rdat)
    throws ServletException, IOException, VeniceServletResult
  {
    // Get the community.
    CommunityContext comm = getCommunityParameter(mphandler,user,true,null);
    changeMenuCommunity(request,comm);
    String target = "sigadmin?cmd=P&sig=" + comm.getCommunityID();
    if (!(comm.canModifyProfile()))
      return new ErrorBox("Community Error","You are not permitted to modify this community's profile.",
			  target);

    if (isImageButtonClicked(mphandler,"cancel"))
      throw new RedirectResult(target);

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

      } // end if

      if (!(mphandler.getContentType("thepic").startsWith("image/")))
      { // must be an image type we uploaded!
	logger.error("Error: 'thepic' not an image type");
	return new ErrorBox(null,"You did not upload an image file.  Try again.",
			    "commlogo?sig=" + comm.getCommunityID());

      } // end if

      try
      { // get the real picture (normalized to 110x65 size)
	ImageLengthPair real_pic = ImageNormalizer.normalizeImage(mphandler.getFileContentStream("thepic"),
								  engine.getCommunityLogoSize(),"jpeg");

	// set the community logo data!
	ContactInfo ci = comm.getContactInfo();
	ci.setPhotoData(request.getContextPath() + "/imagedata/","image/jpeg",real_pic.getLength(),
			real_pic.getData());
	comm.putContactInfo(ci);

	// Jump back to the profile form.
	clearMenu(request);  // allow the menu to be redisplayed
	throw new RedirectResult(target);
								  
      } // end try
      catch (ServletMultipartException smpe)
      { // the servlet multipart parser screwed up
	logger.error("Servlet multipart error:",smpe);
	return new ErrorBox(null,"Internal Error: " + smpe.getMessage(),target);

      } // end catch
      catch (ImageNormalizerException ine)
      { // the image was not valid
	logger.error("Image normalizer error:",ine);
	return new ErrorBox(null,ine.getMessage(),"commlogo?sig=" + comm.getCommunityID());

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

      } // end catch
      catch (AccessError ae)
      { // email exception (WTF?)
	logger.error("Access error:",ae);
	return new ErrorBox(null,"Access error: " + ae.getMessage(),target);

      } // end catch

    } // end if
    else
    { // the button must be wrong!
      logger.error("no known button click on CommunityLogo.doPost");
      return new ErrorBox("Internal Error","Unknown command button pressed",target);

    } // end else

  } // end doVenicePost

} // end class CommunityLogo
