/*
 * BEGIN FLOCK GPL
 *
 * Copyright Flock Inc. 2005-2009
 * http://flock.com
 *
 * This file may be used under the terms of the
 * GNU General Public License Version 2 or later (the "GPL"),
 * http://www.gnu.org/licenses/gpl.html
 *
 * 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.
 *
 * END FLOCK GPL
 */

#include "flockTokenizer.h"

#include "nsIDOMTreeWalker.h"

#include "nsCOMPtr.h"
#include "nsStringAPI.h"


NS_IMPL_ISUPPORTS2(flockTokenizer, flockITokenizer, nsIDOMNodeFilter)


flockTokenizer::flockTokenizer()
{
}

flockTokenizer::~flockTokenizer()
{
}

NS_IMETHODIMP
flockTokenizer::TokenizeDOMNode(nsIDOMDocumentTraversal *aDocumentTraversal,
                                nsIDOMNode *aDOMNode,
                                nsAString &tokenString)
{
  nsresult rv;

  nsAutoString text;

  nsCOMPtr<nsIDOMTreeWalker> treeWalker;
  rv = aDocumentTraversal->CreateTreeWalker(aDOMNode,
                                            (SHOW_TEXT | SHOW_CDATA_SECTION |
                                             SHOW_ELEMENT),
                                            this, PR_FALSE,
                                            getter_AddRefs(treeWalker));
  NS_ENSURE_SUCCESS(rv, rv);
  
  nsCOMPtr<nsIDOMNode> node;
  rv = treeWalker->NextNode(getter_AddRefs(node));
  NS_ENSURE_SUCCESS(rv, rv);
  
  while (node) {
    PRUint16 nodeType;
    rv = node->GetNodeType(&nodeType);
    NS_ENSURE_SUCCESS(rv, rv);

    if (nodeType != nsIDOMNode::ELEMENT_NODE) {
      nsAutoString nodeValue;
      rv = node->GetNodeValue(nodeValue);
      NS_ENSURE_SUCCESS(rv, rv);
      text += nodeValue;
    }

    rv = treeWalker->NextNode(getter_AddRefs(node));
    NS_ENSURE_SUCCESS(rv, rv);
  }

  CompressWhitespace(text);
  tokenString = text;

  return NS_OK;
}

NS_IMETHODIMP
flockTokenizer::AcceptNode(nsIDOMNode *aDOMNode,
                           PRInt16 *filterValue)
{
  nsresult rv;
	
  nsAutoString localName;
  rv = aDOMNode->GetLocalName(localName);
  NS_ENSURE_SUCCESS(rv, rv);
 
  if (!localName.EqualsLiteral("SCRIPT") &&
      !localName.EqualsLiteral("NOSCRIPT")) {
    *filterValue = FILTER_ACCEPT;
  } else {
    *filterValue = FILTER_REJECT;
  }

  return NS_OK;
}
