/*
 * 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.ExecuteQuery;
import blanco.db.conf.QueryLoader;
import blanco.db.exception.BlancoDbException;
import blanco.ig.expander.Value;

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

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

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

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

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

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

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

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

    protected boolean isSingleRow() {
        boolean result = false;

        String single = getTargetElement().getAttribute("single");

        //assert single != null;

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

    public ExecuteQuery getResult() {
        return _result;
    }
}