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

import java.util.Iterator;

import org.w3c.dom.Element;

import blanco.db.BlancoDbConstants;
import blanco.db.conf.QueryLoader;
import blanco.db.conf.SelectQuery;
import blanco.db.exception.BlancoDbException;
import blanco.ig.expander.Value;

/**
 * @author Yasuo Nakanishi
 */
public class SelectQueryLoader extends QueryLoader {
    private SelectQuery _result = null;

    public SelectQueryLoader(String directory) {
        super(directory);
    }

    public SelectQuery getResult() {
        return _result;
    }

    protected void validateQuery() throws BlancoDbException {
        Element selectQuery = getTargetElement();

        if (!findTargetElement(BlancoDbConstants.QUERY_ITERATOR, getPath()
                .getName())) {
            throw new RuntimeException("クエリが見つかりませんでした。Name:"
                    + getPath().getName());
        }

        if (selectQuery.getAttribute("name").equals("")) {
            throw new RuntimeException(BlancoDbConstants.QUERY_ITERATOR
                    + "/@nameが設定されてません。");
        }
        Element query = (Element) selectQuery.getElementsByTagName("query")
                .item(0);
        if (query == null) {
            throw new RuntimeException(BlancoDbConstants.QUERY_ITERATOR
                    + "/query要素がありません。");
        }
        if (getQuery().equals("")) {
            throw new RuntimeException("クエリが指定されていません。");
        }
    }

    protected void parse() {
        _result = new SelectQuery(getPath());

        _result.setQuery(getQuery());
        if (exsistAttribute(getTargetElement(), "single")) {
            _result.setSingle(isSingleRow());
        } else {
            _result.setSingle(false);
        }

        if (exsistAttribute(getTargetElement(), "scroll")) {
            String value = getTargetElement().getAttribute("scroll");
            _result.setScrollInterface(value);
        }

        if (exsistAttribute(getTargetElement(), "updatable")) {
            String value = getTargetElement().getAttribute("updatable");
            _result.setEnableUpdatableInterface(Boolean.valueOf(value)
                    .booleanValue());
        }

        Iterator i = getParameters().iterator();
        while (i.hasNext()) {
            _result.addParameter((Value) i.next());
        }
    }

    private boolean isSingleRow() {
        boolean result = false;
        Element element = getTargetElement();
        String single = element.getAttribute("single");

        //assert single != null;

        if (single.equals("true")) {
            result = true;
        }
        return result;
    }
}