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

import java.sql.*;
import com.silverwrist.util.StringUtil;
import com.silverwrist.venice.htmlcheck.Rewriter;
import com.silverwrist.venice.htmlcheck.RewriterServices;
import com.silverwrist.venice.htmlcheck.MarkupData;
import com.silverwrist.venice.except.ValidationException;
import com.silverwrist.venice.util.IDUtils;

public class PostLinkRewriter implements Rewriter
{
  /*--------------------------------------------------------------------------------
   * Static data members
   *--------------------------------------------------------------------------------
   */

  public static final String URI_PREFIX = "x-postlink:";

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

  private DataPool datapool;

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

  public PostLinkRewriter(DataPool datapool)
  {
    this.datapool = datapool;

  } // end constructor

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

  private static final String buildPostLink(PostLinkDecoder pl, PostLinkDecoderContext ctxt)
  {
    StringBuffer b = new StringBuffer(URI_PREFIX);
    boolean started = false;
    if (pl.getCommunity()==null)
      b.append(ctxt.getCommunityName());
    else
    { // append the real community name
      started = true;
      b.append(pl.getCommunity());

    } // end else

    b.append('!');
    if (pl.getConference()==null)
    { // need to default the context
      if (started)
	return b.toString();
      b.append(ctxt.getConferenceName());

    } // end if
    else
    { // append the proper conference name
      started = true;
      b.append(pl.getConference());

    } // end else

    b.append('.');
    if (pl.getTopic()==-1)
    { // need to default the topic number
      if (started)
	return b.toString();
      b.append(ctxt.getTopicNumber());

    } // end if
    else
    { // append the proper topic number
      started = true;
      b.append(pl.getTopic());

    } // end else

    // append the post link information, if applicable
    b.append('.');
    if (pl.getFirstPost()==-1)
      return b.toString();
    b.append(pl.getFirstPost());
    if (pl.getFirstPost()==pl.getLastPost())
      return b.toString();
    b.append('-');
    if (pl.getLastPost()==-1)
      return b.toString();
    b.append(pl.getLastPost());
    return b.toString();

  } // end buildPostLink

  /*--------------------------------------------------------------------------------
   * Implementations from interface Rewriter
   *--------------------------------------------------------------------------------
   */

  public String getName()
  {
    return null;

  } // end getName

  public MarkupData rewrite(String data, RewriterServices svc)
  {
    PostLinkDecoderContext ctxt;

    try
    { // attempt to get the decoder context
      ctxt = (PostLinkDecoderContext)(svc.getRewriterContextValue("PostLinkDecoderContext"));
      if (ctxt==null)
	return null;  // decoder can't function

    } // end try
    catch (ClassCastException x)
    { // decoder can't function without the context
      return null;

    } // end catch

    PostLinkDecoder pl;

    try
    { // create the post link decoder
      pl = new PostLinkDecoder(data);

      if (pl.needDatabaseVerification())
      { // open up a database connection and verify the community/conference names
	Connection conn = null;

	try
	{ // verify against the database
	  conn = datapool.getConnection();
	  pl.verifyNames(conn);

	} // end try
	catch (SQLException e)
	{ // just return null on failures
	  return null;

	} // end catch
	finally
	{ // release the connection when we're done
	  datapool.releaseConnection(conn);

	} // end finally

      } // end if

    } // end try
    catch (ValidationException ve)
    { // we can't validate the post link - just bail out
      return null;

    } // end catch

    // build the necessary markup and return it
    StringBuffer open_a = new StringBuffer("<A HREF=\"");
    open_a.append(buildPostLink(pl,ctxt)).append("\"");
    String catenate = svc.getRewriterAttrValue("ANCHORTAIL");
    if (!(StringUtil.isStringEmpty(catenate)))
      open_a.append(' ').append(catenate);
    open_a.append('>');
    return new MarkupData(open_a.toString(),data,"</A>");

  } // end rewrite

} // end class PostLinkRewriter
