/*
 * 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;

import java.io.File;
import java.io.IOException;
import java.util.HashSet;
import java.util.Set;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.trix.cuery.filter.Filter;
import org.trix.cuery.filter.ProcessingFilter;
import org.trix.cuery.parser.CueryParser;
import org.trix.cuery.util.CSSUtil;
import org.trix.cuery.util.DOMUtil;

import org.w3c.css.sac.Selector;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;

import org.xml.sax.SAXException;

/**
 * DOCUMENT.
 * 
 * @author <a href="mailto:Teletha.T@gmail.com">Teletha Testarossa</a>
 * @version $ Id: CSSQuery.java,v 1.07 2005/08/05 15:08:13 Teletha Exp $
 */
public class CSSQuery {

    /** The css parser. */
    private static final CueryParser PARSER = new CueryParser();

    /** The root document. */
    private final Document document;

    /**
     * Create CSSQuery instance.
     * 
     * @param path A path to the target xml document to parse.
     * @throws IOException If this file has a I/O error.
     */
    public CSSQuery(String path) throws IOException {
        this(new File(path));
    }

    /**
     * Create CSSQuery instance.
     * 
     * @param file A target xml document to parse.
     * @throws IOException If this file has a I/O error.
     */
    public CSSQuery(File file) throws IOException {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        factory.setNamespaceAware(true);

        try {
            DocumentBuilder builder = factory.newDocumentBuilder();

            this.document = builder.parse(file);
        } catch (ParserConfigurationException e) {
            throw new IOException(e.getMessage());
        } catch (SAXException e) {
            throw new IOException(e.getMessage());
        }
    }

    /**
     * Create CSSQuery instance.
     * 
     * @param document A root document to parse.
     */
    public CSSQuery(Document document) {
        this.document = document;
    }

    /**
     * Query css selector and retrieve elements from the document.
     * 
     * @param expression A css selector expression.
     * @return All mathched elements.
     */
    public Set<Element> select(String expression) {
        return query(document, PARSER.parseSelector(expression));
    }

    /**
     * Query css selector and retrieve elements from the document.
     * 
     * @param selector A css selector.
     * @return All mathched elements.
     */
    public Set<Element> select(Selector selector) {
        return query(document, selector);
    }

    /**
     * Query css selector and retrieve elements.
     * 
     * @param source A source to start parsing.
     * @param selector A css selector.
     * @return All mathched elements.
     */
    private Set<Element> query(Node source, Selector selector) {
        Filter filter = CSSUtil.converte(selector);

        if (filter instanceof ProcessingFilter) {
            ProcessingFilter processing = (ProcessingFilter) selector;
            Set<Element> results = query(source, processing.getSelector());

            // check size
            if (results.size() == 0) {
                return DOMUtil.EMPTY_SET;
            }

            Set<Element> container = new HashSet<Element>();

            // retrieve
            for (Element result : results) {
                processing.process(container, result);
            }
            return container;
        } else {
            return DOMUtil.retrieveElements(source, filter, true);
        }
    }
}
