/*
 * blancoDb
 * Copyright (C) 2004-2005 Yasuo Nakanishi
 * 
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 */
package blanco.db.conf;

import java.util.ArrayList;
import java.util.List;

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

import blanco.ig.expander.Type;
import blanco.ig.expander.Value;

/**
 * @author Yasuo Nakanishi
 */
public class XmlQuery {
    private Element _targetElement = null;

    public XmlQuery(Element element) {
        _targetElement = element;
    }

    /**
     * Query(SQL文)を取得します。
     * 
     * @return
     */
    public String getQuery() {
        StringBuffer sb = new StringBuffer();

        Element query = (Element) _targetElement.getElementsByTagName("query")
                .item(0);
        NodeList list = query.getChildNodes();

        Node node = null;
        CharacterData data = null;
        int type = 0;
        int length = list.getLength();
        for (int i = 0; i < length; i++) {
            node = list.item(i);
            type = node.getNodeType();
            if (type == Node.TEXT_NODE || type == Node.CDATA_SECTION_NODE) {
                data = (CharacterData) node;
                sb.append(data.getData());
            }
        }
        return sb.toString();
    }

    /**
     * parametersエレメントを探し当て、その子ノードであるparameterエレメントを一覧取得します。
     * 
     * @return
     */
    public List getParameters() {
        List result = new ArrayList();

        Element parameters = (Element) _targetElement.getElementsByTagName(
                "parameters").item(0);

        NodeList nodeList = null;
        if (parameters != null) {
            nodeList = parameters.getElementsByTagName("parameter");
        }

        if (nodeList != null) {
            Element parameter = null;
            int length = nodeList.getLength();
            for (int i = 0; i < length; i++) {
                parameter = (Element) nodeList.item(i);
                String name = parameter.getAttribute("name");
                result.add(new Value(new Type(parameter.getAttribute("type")),
                        name));
            }
        }
        return result;
    }

    public Element getTarget() {
        return _targetElement;
    }

    public boolean hasScroll() {
        return _targetElement.hasAttribute("scroll");
    }

    public boolean hasUpdatable() {
        return _targetElement.hasAttribute("updatable");
    }

    public boolean hasSingle() {
        return _targetElement.hasAttribute("single");
    }
}