/*
 * 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.ui.conf.view;

import java.awt.Dimension;
import java.util.*;
import javax.servlet.*;
import org.apache.log4j.*;
import com.silverwrist.util.StringUtil;
import com.silverwrist.venice.core.*;
import com.silverwrist.venice.except.*;
import com.silverwrist.venice.ui.*;
import com.silverwrist.venice.ui.conf.*;
import com.silverwrist.venice.ui.helpers.HTMLRendering;
import com.silverwrist.venice.ui.servlet.RequestImpl;

public class PostsView implements ContentJSP
{
  /*--------------------------------------------------------------------------------
   * Static data members
   *--------------------------------------------------------------------------------
   */

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

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

  private CommunityContext comm;
  private ConferenceContext conf;
  private TopicContext topic;
  private String qid = null;
  private int first = 0;
  private int last;
  private int unread;
  private boolean show_advanced = false;
  private boolean no_bozos = false;
  private RequestInput rinput = null;
  private HTMLRendering html = null;
  private List messages = Collections.EMPTY_LIST;
  private TopicVisitOrder tvo = null;
  private String topic_stem = "";
  private String top_custom = "";
  private String bottom_custom = "";
  private Dimension photo_dims = null;
  private Map photo_map = null;
  private Set bozo_uids = new HashSet();
  private String title = "";
  private String subtitle = "";

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

  public PostsView(CommunityContext comm, CurrentConference currc)
  {
    this.comm = comm;
    this.conf = currc.getConference();
    this.topic = currc.getTopic();
    this.last = this.topic.getTotalMessages() - 1;
    this.unread = this.topic.getUnreadMessages();

  } // end constructor

  /*--------------------------------------------------------------------------------
   * Implementations from interface Content
   *--------------------------------------------------------------------------------
   */

  public boolean needFrame()
  {
    return true;

  } // end needFrame

  public int getMenuSelector()
  {
    return MENU_SELECTOR_COMMUNITY;

  } // end getMenuSelector

  public String getPageTitle(RequestOutput ro)
  {
    return title + ": " + subtitle;

  } // end getPageTitle

  public String getPageQID()
  {
    return qid;

  } // end getPageQID

  /*--------------------------------------------------------------------------------
   * Implementations from interface ContentJSP
   *--------------------------------------------------------------------------------
   */

  public String getJSPName()
  {
    return "conf/posts.jsp";

  } // end getJSPName

  public void initialize(RequestInput req)
  {
    rinput = req;
    html = (HTMLRendering)(req.queryService(HTMLRendering.class));

  } // end initialize

  public void terminate(RequestInput req)
  {
    rinput = null;
    html = null;

  } // end terminate

  /*--------------------------------------------------------------------------------
   * External operations
   *--------------------------------------------------------------------------------
   */

  public final CommunityContext getCommunity()
  {
    return comm;

  } // end getCommunity

  public final ConferenceContext getConference()
  {
    return conf;

  } // end getConference

  public final TopicContext getTopic()
  {
    return topic;

  } // end getTopic

  public final void setPageQID(String v)
  {
    if (rinput==null)
      qid = v;

  } // end setPageQID

  public final int getFirst()
  {
    return first;

  } // end getFirst

  public final void setFirst(int v)
  {
    if (rinput==null)
      first = v;

  } // end setFirst

  public final int getLast()
  {
    return last;

  } // end getLast

  public final void setLast(int v)
  {
    if (rinput==null)
      last = v;

  } // end setLast

  public final int getUnread()
  {
    return unread;

  } // end getUnread

  public final void setUnread(int v)
  {
    if (rinput==null)
      unread = v;

  } // end setUnread

  public final boolean getShowAdvanced()
  {
    return show_advanced;

  } // end getShowAdvanced

  public final void setShowAdvanced(boolean v)
  {
    if (rinput==null)
      show_advanced = v;

  } // end setShowAdvanced

  public final boolean getNoBozos()
  {
    return no_bozos;

  } // end getNoBozos

  public final void setNoBozos(boolean v)
  {
    if (rinput==null)
      no_bozos = v;

  } // end setNoBozos

  public final List getMessages()
  {
    return messages;

  } // end getMessages

  public final void setMessages(List v)
  {
    if (rinput==null)
      messages = v;

  } // end setMessages

  public final TopicVisitOrder getTopicVisitOrder()
  {
    return tvo;

  } // end getTopicVisitOrder

  public final void setTopicVisitOrder(TopicVisitOrder v)
  {
    if (rinput==null)
      tvo = v;

  } // end setTopicVisitOrder

  public final String getTopicStem()
  {
    return topic_stem;

  } // end getTopicStem

  public final void setTopicStem(String v)
  {
    if (rinput==null)
      topic_stem = v;

  } // end setTopicStem

  public final String getTopCustom()
  {
    return top_custom;

  } // end getTopCustom

  public final void setTopCustom(String v)
  {
    if (rinput==null)
      top_custom = ((v==null) ? "" : v);

  } // end setTopCustom

  public final String getBottomCustom()
  {
    return bottom_custom;

  } // end getBottomCustom

  public final void setBottomCustom(String v)
  {
    if (rinput==null)
      bottom_custom = ((v==null) ? "" : v);

  } // end setBottomCustom

  public final Dimension getPhotoDims()
  {
    return photo_dims;

  } // end getPhotoDims

  public final void setPhotoDims(Dimension v)
  {
    if (rinput==null)
      photo_dims = v;

  } // end setPhotoDims

  public final Map getPhotoMap()
  {
    return photo_map;

  } // end getPhotoMap

  public final Set getBozoUIDs()
  {
    return bozo_uids;

  } // end getBozoUIDs

  public final String getTitle()
  {
    return title;

  } // end getTitle

  public final void setTitle(String v)
  {
    if (rinput==null)
      title = ((v==null) ? "" : v);

  } // end setTitle

  public final String getSubtitle()
  {
    return subtitle;

  } // end getSubtitle

  public final void setSubtitle(String v)
  {
    if (rinput==null)
      subtitle = ((v==null) ? "" : v);

  } // end setSubtitle

  public final void buildInternals(UserContext user) throws DataException
  {
    if (rinput!=null)
      return;

    if (photo_dims!=null)
      photo_map = new HashMap();

    HashSet saw_users = new HashSet();
    Iterator it = messages.iterator();
    boolean get_photo = true;
    while (it.hasNext())
    { // get the user names of all users on the page
      TopicMessageContext msg = (TopicMessageContext)(it.next());
      Integer the_uid = new Integer(msg.getCreatorUID());
      if (!(saw_users.contains(the_uid)))
      { // only check a UID once
	saw_users.add(the_uid);
	get_photo = true;
	if (topic.isBozo(the_uid.intValue()))
	{ // this user is filtered
	  bozo_uids.add(the_uid);
	  get_photo = no_bozos;  // get photo if bozo filter overridden

	} // end if

	if (get_photo && (photo_dims!=null))
	{ // store the user photo URL
	  String url = user.getProfile(the_uid.intValue()).getPhotoURL();
	  if (url!=null)
	    photo_map.put(the_uid,url);

	} // end if

      } // end if
      // else ignore the uID

    } // end while

  } // end buildInternals

  public final boolean canDoNextTopic()
  {
    if (tvo!=null)
      return tvo.isNext();
    else
      return false;

  } // end canDoNextTopic

  public final short getNextTopic()
  {
    if (tvo!=null)
      return tvo.getNext();
    else
      return -1;

  } // else getNextTopic

  public final int getPageSize()
  {
    return ((rinput==null) ? 0 : rinput.getEngine().getNumPostsPerPage());

  } // end getPageSize

  public final boolean bozoFilterUser(int uid)
  {
    if (no_bozos)
      return false;
    else
      return bozo_uids.contains(new Integer(uid));

  } // end bozoFilterUser

  public final boolean showBozoFilteredIndicator(int uid)
  {
    if (no_bozos)
      return bozo_uids.contains(new Integer(uid));
    else
      return false;

  } // end showBozoFilteredIndicator

  public final String getUserPhotoTag(RequestOutput ro, int uid)
  {
    if ((photo_dims==null) || (photo_map==null))
      return "";  // user photos not enabled
    HTMLRendering html = (HTMLRendering)(ro.queryService(HTMLRendering.class));
    return html.getUserPhotoTag((String)(photo_map.get(new Integer(uid))),photo_dims);

  } // end getUserPhotoTag

  public final String formatDate(Date date)
  {
    return ((html==null) ? null : html.formatDate(date));

  } // end formatDate

  public final boolean showFilterButton(int uid)
  {
    return !(bozo_uids.contains(new Integer(uid))) && topic.canSetBozo(uid);

  } // end showFilterButton

  /*--------------------------------------------------------------------------------
   * External static operations
   *--------------------------------------------------------------------------------
   */

  public static final PostsView get(ServletRequest sreq) throws ServletException
  {
    Object obj = sreq.getAttribute(RequestImpl.REQUEST_CONTENT);
    if (obj==null)
      throw new ServletException("PostsView.get: unable to get request content");
    if (obj instanceof PostsView)
      return (PostsView)obj;
    throw new ServletException("PostsView.get: request content is not a PostsView object");

  } // end get

  public static final String getPosterName(TopicMessageContext msg)
  {
    try
    { // have to guard agains a DataException here
      return msg.getCreatorName();

    } // end try
    catch (DataException de)
    { // just return "unknown" on failure
      return "(unknown)";

    } // end catch

  } // end getPosterName

  public static final String getMessageBodyText(TopicMessageContext msg)
  {
    try
    { // have to guard against a DataException here
      return msg.getBodyText();

    } // end try
    catch (DataException de)
    { // just return an error message
      return "<EM>(Unable to retrieve message data: " + StringUtil.encodeHTML(de.getMessage()) + ")</EM>";

    } // end catch

  } // end getMessageBodyText

  public static final boolean displayAttachmentInNewWindow(TopicMessageContext msg)
  {
    if (!(msg.hasAttachment()))
      return false;
    String type = msg.getAttachmentType();
    return (type.startsWith("text/") || type.startsWith("image/"));

  } // end displayAttachmentInNewWindow

} // end class PostView

