/*
 * 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.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import javax.xml.parsers.ParserConfigurationException;

import org.xml.sax.SAXException;

import blanco.db.conf.BlancoDbMetadata;
import blanco.db.conf.BlancoDbSetting;
import blanco.db.conf.ExecuteQuery;
import blanco.db.definition.QueryInvoker;
import blanco.db.exception.BlancoDbException;
import blanco.ig.tool.ConsolePrinter;

/**
 * @author Yasuo Nakanishi
 */
public class InvokerCollector {
    private BlancoDbSetting _setting = null;

    private BlancoDbMetadata _metadata = null;

    private List _margedQuery = new ArrayList();

    private ConsolePrinter _printer = ConsolePrinter.get();

    public List collect(BlancoDbSetting setting, BlancoDbMetadata metadata)
            throws SAXException, IOException, ParserConfigurationException,
            BlancoDbException {
        _setting = setting;
        _metadata = metadata;

        load();

        final List _result = new ArrayList();

        Iterator iterator = _margedQuery.iterator();
        while (iterator.hasNext()) {
            // Invokerはロールバック可能性が保証されていない可能性を考慮し、
            // メタ調査時には実行は行いません。そのためSQL例外は発生しません。
            QueryInvoker invoker = new QueryInvoker((ExecuteQuery) iterator
                    .next());
            _result.add(invoker);

        }
        return _result;
    }

    private void load() throws SAXException, IOException,
            ParserConfigurationException, BlancoDbException {
        ExecuteQueryLoader loader = new ExecuteQueryLoader(_setting
                .getQueryDirectory());
        for (int i = 0; i < _metadata.getExecuteQueryCount(); i++) {
            try {
                loader.load(_metadata.getExecuteQuery(i).getQueryPath());
                _margedQuery.add(loader.getResult());
            } catch (FileNotFoundException e) {
                String message = "";
                message += "クエリファイルが見つかりませんでした。";
                message += "次のクエリは作成されません。";
                message += "Name:" + _metadata.getExecuteQuery(i).getName();
                message += ", FilePath:"
                        + _metadata.getExecuteQuery(i).getFilePath();
                _printer.printWarning(message);
            }
        }
    }
}