/*
 * 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) 2003 Eric J. Bowersox/Silverwrist Design Studios.  All Rights Reserved.
 * 
 * Contributor(s): 
 */
package com.silverwrist.dynamo.htmlcheck;

import java.util.*;
import java.util.regex.*;
import org.apache.log4j.Logger;
import com.silverwrist.dynamo.Namespaces;
import com.silverwrist.dynamo.iface.*;
import com.silverwrist.dynamo.util.*;

class RewriteURLs implements HTMLCheckerConfigurator, HTMLRewriter
{
  /*--------------------------------------------------------------------------------
   * Internal class that contains matching information
   *--------------------------------------------------------------------------------
   */

  private static class Match
  {
    /*====================================================================
     * Attributes
     *====================================================================
     */

    private Pattern m_pat;
    private String m_prefix;

    /*====================================================================
     * Constructors
     *====================================================================
     */

    Match(String pattern) throws PatternSyntaxException
    {
      m_pat = Pattern.compile(pattern);
      m_prefix = null;

    } // end constructor

    Match(String pattern, String prefix) throws PatternSyntaxException
    {
      m_pat = Pattern.compile(pattern);
      m_prefix = prefix;

    } // end constructor

    /*====================================================================
     * External operations
     *====================================================================
     */

    boolean match(String input)
    {
      return m_pat.matcher(input).matches();

    } // end match

    String prefixate(String input)
    {
      if (m_prefix==null)
	return input;
      else
	return m_prefix + input;

    } // end prefixate

  } // end class Match

  /*--------------------------------------------------------------------------------
   * Static data members
   *--------------------------------------------------------------------------------
   */

  private static Logger logger = Logger.getLogger(RewriteURLs.class);

  private static final String DEFAULT_TARGET = "Wander";

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

  private List m_matchers;

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

  RewriteURLs()
  {
    ArrayList l = new ArrayList();
    try
    { // pre-compile all our regex patterns
      // recognize: http://<host>[:<port>]...
      l.add(new Match("^http://[A-Za-z0-9-]+(\\.[A-Za-z0-9-]+)*(:[0-9]+)?(/.*)?$"));

      // recognize: ftp://<host>[:<port>]...
      l.add(new Match("^ftp://[A-Za-z0-9-]+(\\.[A-Za-z0-9-]+)*(:[0-9]+)?(/.*)?$"));

      // recognize: gopher://<host>[:<port>]...
      l.add(new Match("^gopher://[A-Za-z0-9-]+(\\.[A-Za-z0-9-]+)*(:[0-9]+)?(/.*)?$"));

      // recognize: mailto:<valid E-mail address>[?queryinfo]
      l.add(new Match("^mailto:[A-Za-z0-9!#$%*+-/=?^_`{|}~.]+@[A-Za-z0-9-]+(\\.[A-Za-z0-9-]+)*(\\?.+)?$"));

      // recognize: news:<newsgroup name>
      l.add(new Match("^news:[A-Za-z0-9-_]+(\\.[A-Za-z0-9-_]+)*$"));

      // recognize: news:<message-id>
      l.add(new Match("^news:.*@[A-Za-z0-9-]+(\\.[A-Za-z0-9-]+)*$"));

      // recognize: nntp://<host>[:<port>]/<newsgroup>/<article>
      l.add(new
            Match("^nntp://[A-Za-z0-9-]+(\\.[A-Za-z0-9-]+)*(:[0-9]+)?/[A-Za-z0-9-_]+(\\.[A-Za-z0-9-_]+)*/[0-9]+$"));

      // recognize: telnet://<host>[:<port>]
      l.add(new Match("^telnet://[A-Za-z0-9-]+(\\.[A-Za-z0-9-]+)*(:[0-9]+)?$"));

      // recognize: tn3270://<host>[:<port>]
      l.add(new Match("^tn3270://[A-Za-z0-9-]+(\\.[A-Za-z0-9-]+)*(:[0-9]+)?$"));

      // recognize "www.whatever" and tack http:// onto the front
      l.add(new Match("^www\\.[A-Za-z0-9-]+(\\.[A-Za-z0-9-]+)*(/.*)?$","http://"));

      // recognize "ftp.whatever" and tack ftp:// onto the front
      l.add(new Match("^ftp\\.[A-Za-z0-9-]+(\\.[A-Za-z0-9-]+)*(/.*)?$","ftp://"));

      // recognize "gopher.whatever" and tack gopher:// onto the front
      l.add(new Match("^gopher\\.[A-Za-z0-9-]+(\\.[A-Za-z0-9-]+)*(/.*)?$","gopher://"));

    } // end try
    catch (PatternSyntaxException pe)
    { // log an error, all we can do
      logger.fatal("Pattern compilation error in RewriteEMailAddresses",pe);

    } // end catch

    l.trimToSize();
    m_matchers = Collections.unmodifiableList(l);

  } // end constructor

  /*--------------------------------------------------------------------------------
   * Implementations from interface HTMLCheckerConfigurator
   *--------------------------------------------------------------------------------
   */

  public void configure(HTMLCheckerProfile profile)
  {
    boolean enable =
        ((Boolean)(PropertyUtils.getPropertyDefault(profile,Namespaces.HTMLCHECKER_PROPERTIES_NAMESPACE,
						    "rewrite.URL.string",Boolean.FALSE))).booleanValue();
    if (enable)
      profile.addStringRewriter(this);
    enable = ((Boolean)(PropertyUtils.getPropertyDefault(profile,Namespaces.HTMLCHECKER_PROPERTIES_NAMESPACE,
							 "rewrite.URL.tag",Boolean.FALSE))).booleanValue();
    if (enable)
      profile.addTagRewriter(this);
    enable = ((Boolean)(PropertyUtils.getPropertyDefault(profile,Namespaces.HTMLCHECKER_PROPERTIES_NAMESPACE,
							 "rewrite.URL.paren",Boolean.FALSE))).booleanValue();
    if (enable)
      profile.addParenRewriter(this);
    enable = ((Boolean)(PropertyUtils.getPropertyDefault(profile,Namespaces.HTMLCHECKER_PROPERTIES_NAMESPACE,
							 "rewrite.URL.bracket",Boolean.FALSE))).booleanValue();
    if (enable)
      profile.addBracketRewriter(this);
    enable = ((Boolean)(PropertyUtils.getPropertyDefault(profile,Namespaces.HTMLCHECKER_PROPERTIES_NAMESPACE,
							 "rewrite.URL.brace",Boolean.FALSE))).booleanValue();
    if (enable)
      profile.addBraceRewriter(this);

  } // end configure

  /*--------------------------------------------------------------------------------
   * Implementations from interface HTMLRewriter
   *--------------------------------------------------------------------------------
   */

  public QualifiedNameKey getName()
  {
    return null;

  } // end getName

  public MarkupData rewrite(String data, String prefix, String suffix, HTMLRewriterSite site)
  {
    Iterator it = m_matchers.iterator();
    while (it.hasNext())
    { // look for a matching element
      Match x = (Match)(it.next());
      if (x.match(data))
      { // found it! build the <A> tag for the markup
	StringBuffer buf = new StringBuffer("<a href=\"");
	buf.append(x.prefixate(data)).append("\" target=\"");
	String target = site.getAttribute(Namespaces.HTMLCHECKER_PROPERTIES_NAMESPACE,"default.A.target");
	if (target==null)
	  target = DEFAULT_TARGET;
	buf.append(target).append("\">");

	return new MarkupData(prefix,buf.toString(),data,"</a>",suffix);

      } // end if

    } // end while

    return null;  // punt

  } // end rewrite

} // end class RewriteURLs
