/*
 * 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.core.impl;

import java.util.*;
import org.apache.log4j.*;
import com.silverwrist.util.StringUtil;
import com.silverwrist.venice.core.internals.*;
import com.silverwrist.venice.except.*;
import com.silverwrist.venice.htmlcheck.*;

class PostDeliveryAgent extends Thread
{
  /*--------------------------------------------------------------------------------
   * Static data members
   *--------------------------------------------------------------------------------
   */

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

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

  private EnvEngine env;                    // the environment
  private String post_text;                 // the raw post text
  private String post_pseud;                // the raw pseud
  private List delivery_addresses;          // the addresses to deliver to
  private Map vars;                         // the replacement variables for the templates

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

  PostDeliveryAgent(EnvConference env, String txt, String pseud, String topicname, int topicnum, List addrs)
  {
    super();
    setDaemon(false);

    // Save the calling data.
    this.env = env;
    this.post_text = txt;
    this.post_pseud = pseud;
    this.delivery_addresses = addrs;

    // Now build the substitution table used to format the templates.
    HashMap xvars = new HashMap();
    xvars.put("message.poster",env.getUserName());
    xvars.put("topic.name",topicname);
    xvars.put("topic.locator",env.getCommunityAlias() + "!" + env.getConferenceAlias() + "." + topicnum);
    xvars.put("conference.name",env.getConferenceName());
    xvars.put("community.name",env.getCommunityName());
    vars = Collections.unmodifiableMap(xvars);

  } // end constructor

  /*--------------------------------------------------------------------------------
   * Overrides from class Thread
   *--------------------------------------------------------------------------------
   */

  public void run()
  {
    NDC.push("PostDeliveryAgent");

    try
    { // kick off the delivery process
      if (logger.isDebugEnabled())
	logger.debug("PostDeliveryAgent started by " + vars.get("message.poster") + " with "
		     + delivery_addresses.size() + " mails to deliver");

      // To start off with, both the text and the pseud need to be "stripped" of all HTML.
      String real_text = null;
      String real_pseud = null;
      try
      { // run both arguments through the HTML checker
	HTMLChecker mail_checker = env.getEngine().createCheckerObject(EngineBackend.HTMLC_MAIL_POST);
	mail_checker.append(post_text);
	mail_checker.finish();
	real_text = mail_checker.getValue();
	mail_checker.reset();
	mail_checker.append(post_pseud);
	mail_checker.finish();
	real_pseud = mail_checker.getValue();

      } // end try
      catch (HTMLCheckerException e)
      { // this isn't right...
	logger.error("PostDeliveryAgent: threw HTMLCheckerException",e);
	throw new InternalStateError("HTMLChecker erroneously throwing exception",e);

      } // end catch

      // Format the three stock message parts.
      String msg_top = StringUtil.replaceAllVariables(env.getStockMessage("mail-post-top"),vars);
      String msg_bot = StringUtil.replaceAllVariables(env.getStockMessage("mail-post-bottom"),vars);
      String msg_subj = StringUtil.replaceAllVariables(env.getStockMessage("subj-mail-post"),vars);

      // Construct the full message body.
      StringBuffer body = new StringBuffer(msg_top);
      body.append("\n\n").append(real_pseud).append("\n\n").append(real_text).append("\n\n");
      body.append(msg_bot).append("\n--\n").append(env.getStockMessage("signature"));

      // Create the emailer object and load it up with most of the data.
      Emailer em = env.getEngine().createEmailer();
      em.setSubject(msg_subj);
      em.setText(body.toString());

      // Deliver the mail to each of the target addresses in turn.
      Iterator it = delivery_addresses.iterator();
      while (it.hasNext())
      { // get ready to deliver the mail...
	String addr = (String)(it.next());
	if (logger.isDebugEnabled())
	  logger.debug("Delivering to " + addr);

	try
	{ // set the recipient and send it out
	  em.setTo(addr);
	  em.send();

	} // end try
	catch (EmailException e)
	{ // log the error and move on
	  logger.error("Caught EmailException when trying to send to " + addr,e);

	} // end catch

      } // end while

    } // end try
    finally
    { // pop the nested diagnostic context before we go
      NDC.pop();

    } // end finally
    
  } // end run

} // end class PostDeliveryAgent
