/*
 * Copyright 2004-2005 The Trix Development Team.
 *
 * 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 org.trix.cuery.util;

import java.util.Collections;
import java.util.HashSet;
import java.util.Set;

import org.trix.cuery.dom.stylesheets.StyleSheetImpl;
import org.trix.cuery.dom.stylesheets.StyleSheetListImpl;
import org.trix.cuery.filter.ClassFilter;
import org.trix.cuery.filter.ElementFilter;
import org.trix.cuery.filter.Filter;
import org.trix.cuery.filter.IDFilter;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.w3c.dom.ProcessingInstruction;
import org.w3c.dom.stylesheets.StyleSheetList;

/**
 * DOCUMENT.
 * 
 * @author <a href="mailto:Teletha.T@gmail.com">Teletha Testarossa</a>
 * @version $ Id: DOMUtil.java,v 1.2 2005/08/04 21:42:37 Teletha Exp $
 */
public final class DOMUtil {

    /** The empty elements. */
    public static final Set<Element> EMPTY_SET = Collections.unmodifiableSet(new HashSet<Element>(0));

    /**
     * Avoid creating DOMUtil instance.
     */
    private DOMUtil() {
    }

    /**
     * Retrieve all descendant elements which are filtered by the class name.
     * 
     * @param source A source node.
     * @param className A class name.
     * @return All matched descendant elements.
     */
    public static Set<Element> getElementsByClassName(Node source, String className) {
        return retrieveElements(source, new ClassFilter(className), true);
    }

    /**
     * Retrieve a element which are filtered by the id. If there is no such element, return null.
     * 
     * @param source A source node.
     * @param id An id.
     * @return A matched element.
     */
    public static Element getElementById(Node source, String id) {
        Set<Element> result = retrieveElements(source, new IDFilter(id), true);

        if (result.size() == 1) {
            return result.iterator().next();
        } else {
            return null;
        }
    }

    /**
     * Retrieve all descendant elements which are filtered by the tag name. Tag name accepts null or
     * zero length value, and these are treated as an asterisk.
     * 
     * @param source A source node.
     * @param tagName A tag name.
     * @return All matched descendant elements.
     */
    public static Set<Element> getElementsByTagName(Node source, String tagName) {
        return retrieveElements(source, new ElementFilter(tagName), true);
    }

    /**
     * Retrieve a previous sibling element. If there is no such element, return null.
     * 
     * @param source A source node to start searching.
     * @return A matched element.
     */
    public static Element getPreviousElement(Node source) {
        // check null
        if (source == null) {
            return null;
        }

        Node previous = source.getPreviousSibling();

        if (previous == null) {
            return null;
        }

        if (previous.getNodeType() == Node.ELEMENT_NODE) {
            return (Element) previous;
        }
        return getPreviousElement(previous);
    }

    /**
     * Retrieve a next sibling element. If there is no such element, return null.
     * 
     * @param source A source node to start searching.
     * @return A matched element.
     */
    public static Element getNextElement(Node source) {
        // check null
        if (source == null) {
            return null;
        }

        Node next = source.getNextSibling();

        if (next == null) {
            return null;
        }

        if (next.getNodeType() == Node.ELEMENT_NODE) {
            return (Element) next;
        }
        return getNextElement(next);
    }

    /**
     * Return stylesheet list from document.
     * 
     * @param document A target document.
     * @return A list of stylesheet.
     */
    public static StyleSheetList getStylesheets(Document document) {
        NodeList children = document.getChildNodes();
        StyleSheetListImpl list = new StyleSheetListImpl();

        for (int i = 0; i < children.getLength(); i++) {
            Node child = children.item(i);

            if (child.getNodeType() == Node.PROCESSING_INSTRUCTION_NODE) {
                ProcessingInstruction pi = (ProcessingInstruction) child;
                list.addStyleSheet(new StyleSheetImpl(pi));
            }
        }
        return list;
    }

    /**
     * Return element position in parent element.
     * 
     * @param element A target element.
     * @return A position.
     */
    public static int getPosition(Element element) {
        // check null
        if (element == null) {
            return -1;
        }

        // check parent
        Node parent = element.getParentNode();

        if (parent == null || parent.getNodeType() != Node.ELEMENT_NODE) {
            return -1;
        }

        int position = 1;
        NodeList nodeList = parent.getChildNodes();

        for (int i = 0; i < nodeList.getLength(); i++) {
            Node current = nodeList.item(i);

            // check element
            if (current.getNodeType() != Node.ELEMENT_NODE) {
                continue;
            }

            // cehck
            if (current == element) {
                return position;
            }
            position++;
        }
        return -1;
    }

    /**
     * Return typed element position in parent element.
     * 
     * @param element A target element.
     * @return A position.
     */
    public static int getTypedPosition(Element element) {
        // check null
        if (element == null) {
            return -1;
        }

        // check parent
        Node parent = element.getParentNode();

        if (parent == null || parent.getNodeType() != Node.ELEMENT_NODE) {
            return -1;
        }

        int position = 1;
        String ns = element.getNamespaceURI();
        String name = element.getLocalName();
        NodeList nodeList = parent.getChildNodes();

        for (int i = 0; i < nodeList.getLength(); i++) {
            Node node = nodeList.item(i);

            // check element
            if (node.getNodeType() != Node.ELEMENT_NODE) {
                continue;
            }

            Element current = (Element) node;

            // check namespace
            if (ns != null && !ns.equals(current.getNamespaceURI())) {
                continue;
            }

            // check local name
            if (!current.getLocalName().equals(name)) {
                continue;
            }

            // cehck
            if (current == element) {
                return position;
            }
            position++;
        }
        return -1;
    }

    /**
     * Check whether this element has a specified token attribute or not.
     * 
     * @param target A target element.
     * @param name A attribute name.
     * @param token A attribute value.
     * @return A result.
     */
    public static boolean hasToken(Element target, String name, String token) {
        // check null
        if (target == null || name == null || name.length() == 0 || token == null || token.length() == 0) {
            return false;
        }

        String attribute = target.getAttribute(name);

        if (attribute == null || attribute.length() < token.length()) {
            return false;
        }

        String[] values = attribute.split(" ");

        for (String value : values) {
            if (value.equals(token)) {
                return true;
            }
        }
        return false;
    }

    /**
     * Retrieve all filtered elements.
     * 
     * @param source A source node.
     * @param filter A filter.
     * @param descendant A flag whether the descendant elements are parsed or not.
     * @return All matched elements.
     */
    public static Set<Element> retrieveElements(Node source, Filter filter, boolean descendant) {
        // check null
        if (source == null) {
            return EMPTY_SET;
        }

        // check node type
        if (source.getNodeType() == Node.DOCUMENT_NODE || source.getNodeType() == Node.ELEMENT_NODE) {
            Set<Element> container = new HashSet<Element>();
            retrieveElements(container, source, filter, descendant);
            return container;
        }
        return EMPTY_SET;
    }

    /**
     * Helper method to collect elements under some filters.
     * 
     * @param container A matched element container.
     * @param source Start searching from this position.
     * @param filter A catch-all filter.
     * @param descendant A flag whether the descendant elements are parsed or not.
     */
    private static void retrieveElements(Set<Element> container, Node source, Filter filter, boolean descendant) {
        // check child
        if (!source.hasChildNodes()) {
            return;
        }

        NodeList children = source.getChildNodes();

        for (int i = 0; i < children.getLength(); i++) {
            Node child = children.item(i);

            if (child.getNodeType() == Node.ELEMENT_NODE) {
                Element element = (Element) child;

                // recursive collection
                if (descendant) {
                    retrieveElements(container, element, filter, descendant);
                }

                // filter
                if (!filter.accept(element)) {
                    continue;
                }
                container.add(element);
            }
        }
    }
}
