// Copyright 2008-2012 severally by the contributors
//
// Licensed under the Apache License, Version 2.0 (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.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package net.sf.practicalxml.xpath;

import java.util.List;

import javax.xml.xpath.XPathFunction;
import javax.xml.xpath.XPathFunctionException;

import org.w3c.dom.Node;
import org.w3c.dom.NodeList;


/**
 *  Common code for the XPath tests.
 */
public abstract class XPathTestHelpers
{
    /**
     *  A standard XPath function implementation that returns the namespace
     *  of the first selected node.
     */
    public static class GetNamespaceSF
    implements XPathFunction
    {
        @SuppressWarnings("rawtypes")
        public Object evaluate(List args)
        throws XPathFunctionException
        {
            NodeList arg = (NodeList)args.get(0);
            return arg.item(0).getNamespaceURI();
        }
    }


    /**
     *  An <code>AbstractFunction</code> implementation that returns the
     *  namespace of the first selected node.
     */
    public static class GetNamespaceAF
    extends AbstractFunction<String>
    {
        public GetNamespaceAF(String nsUri, String name)
        {
            super(nsUri, name);
        }

        @Override
        protected String processArg(int index, Node value, String helper)
        throws Exception
        {
            return value.getNamespaceURI();
        }
    }


    /**
     *  A standard XPath function that counts its invocations, exposing
     *  the count via a public variable. It also returns the count as
     *  its result.
     */
    public static class CountingSF
    implements XPathFunction
    {
        public int calls;

        @SuppressWarnings("rawtypes")
        public Object evaluate(List args) throws XPathFunctionException
        {
            calls++;
            return Integer.valueOf(calls);
        }
    }


    /**
     *  An <code>AbstractFunction</code> that counts its invocations and
     *  exposes this through a public variable. It also returns the count
     *  as its result.
     */
    public static class CountingAF
    extends AbstractFunction<Integer>
    {
        public int count;

        public CountingAF(String nsUri, String name)
        {
            super(nsUri, name);
        }

        @Override
        protected Integer processArg(int index, Node value, Integer helper)
        throws Exception
        {
            return Integer.valueOf(count++);
        }
    }
}
