/*
 * 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 Community System.
 * 
 * The Initial Developer of the Original Code is Eric J. Bowersox <erbo@ricochet.com>,
 * for Silverwrist Design Studios.  Portions created by Eric J. Bowersox are
 * Copyright (C) 2001-2004 Eric J. Bowersox/Silverwrist Design Studios.  All Rights Reserved.
 * 
 * Contributor(s): 
 */
package com.silverwrist.venice.htmlcheck.impl;

import java.net.*;
import org.apache.log4j.Logger;
import org.apache.regexp.*;
import com.silverwrist.util.*;

class TagA extends BalancedTag
{
  /*--------------------------------------------------------------------------------
   * Internal static data
   *--------------------------------------------------------------------------------
   */

  /** The instance of {@link org.apache.log4j.Logger Logger} for use by this class. */
  private static Logger logger = Logger.getLogger(TagA.class);

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

  /** Regular expression program to look for "HREF=" attribute. */
  private REProgram m_href = null;

  /** Regular expression program to look for "TARGET=" attribute. */
  private REProgram m_target = null;

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

  /**
   * Creates a new instance of <code>TagA</code>.
   */
  TagA()
  {
    super("A",false);
    try
    { // compile regular expressions
      RECompiler compiler = new RECompiler();
      m_href = compiler.compile("href\\s*=");
      m_target = compiler.compile("target\\s*=");

    } // end try
    catch (RESyntaxException e)
    { // shouldn't happen
      logger.fatal("got RESyntaxException in TagA",e);

    } // end catch

  } // end constructor

  /*--------------------------------------------------------------------------------
   * Internal operations
   *--------------------------------------------------------------------------------
   */

  /**
   * Extracts an attribute value from the start of the string.  The attribute value may be enclosed
   * in quotes, or may simply be a series of nonblank characters delimited by blanks.
   *
   * @param s The string to extract the attribute value from.
   * @return The attribute value extracted.
   */
  private static final String extractAttribute(String s)
  {
    char[] a = s.toCharArray();
    int i = 0;
    while ((i<a.length) && Character.isWhitespace(a[i]))
      i++;
    if (i==a.length)
      return "";
    int st = i;
    if ((a[st]=='\'') || (a[st]=='\"'))
    { // find quoted string boundaries
      i++;
      while ((i<a.length) && (a[i]!=a[st]))
	i++;
      if (i==a.length)
	return "";
      st++;

    } // end if
    else
    { // skip over non-whitespace
      while ((i<a.length) && !(Character.isWhitespace(a[i])))
	i++;
      // if i==a.length, just take the "rest"

    } // end else

    if (i==a.length)
      return s.substring(st);
    else
      return s.substring(st,i);

  } // end extractAttribute

  /*--------------------------------------------------------------------------------
   * Overrides from class SimpleTag
   *--------------------------------------------------------------------------------
   */

  public String rewriteTagContents(String contents, boolean is_closing, HTMLCheckerBackend context)
  {
    if (is_closing)
      return contents;  // don't bother checking close tags

    // Pull out the HREF= attribute, as that's an "external reference" we need to keep track of.
    RE m = new RE(m_href,RE.MATCH_CASEINDEPENDENT);
    if (m.match(contents))
    { // get the attribute value
      try
      { // turn it into a URL and add it as an external reference
	String s = extractAttribute(contents.substring(m.getParenEnd(0)));
	if (!(StringUtil.isStringEmpty(s)) && s.toLowerCase().startsWith("http:"))
	{ // turn it into the URL and add it
	  URL ref = new URL(s);
	  context.addExternalReference(ref);

	} // end if
	// else ignore me

      } // end try
      catch (MalformedURLException e)
      { // ignore this reference
      } // end catch

    } // end if

    // Look for the TARGET= attribute.
    boolean target_seen = false;
    m = new RE(m_target,RE.MATCH_CASEINDEPENDENT);
    if (m.match(contents))
    { // get the attribute value
      String s = extractAttribute(contents.substring(m.getParenEnd(0)));
      if (!(StringUtil.isStringEmpty(s)))
	target_seen = true;

    } // end if

    if (target_seen)
      return contents;  // no need to alter the string

    String tail = (String)(context.getCheckerAttrValue("ANCHORTAIL"));
    return contents + " " + tail;

  } // end rewriteTagContents

} // end class TagA
