/*
 * 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.expander.query.iterator;

import java.sql.SQLException;

import blanco.db.conf.BlancoDbSetting;
import blanco.db.definition.QueryIterator;
import blanco.db.expander.implementor.BlancoDbImplementor;
import blanco.db.properties.GenerationProperties;
import blanco.db.util.BlancoDbObjectStorage;
import blanco.ig.expander.Value;
import blanco.ig.expander.implementor.Receiver;
import blanco.ig.expander.implementor.Statement;
import blanco.ig.expander.method.MethodExpander;

/**
 * @author Yasuo Nakanishi
 */
public class ExecuteQueryMethod extends MethodExpander {
    private Value _resultSet = null;

    private Value _statement = null;

    private BlancoDbSetting _setting = null;

    private QueryIterator _iterator = null;

    private GenerationProperties _properties = null;

    public ExecuteQueryMethod(QueryIterator iterator) {
        super("executeQuery");

        _iterator = iterator;

        BlancoDbObjectStorage storage = BlancoDbObjectStorage.getInstance();
        _setting = storage.getSetting();
        _properties = storage.getGenerationProperties();
    }

    public void setupSignature() {
        addException(SQLException.class);

        if (_properties.isGenerateJavaDoc()) {
            getJavaDoc().addLine("検索型クエリを実行します。<br>");
        }
    }

    public void implement() {
        BlancoDbImplementor i = new BlancoDbImplementor(getData());

        _statement = getField("Statement");
        _resultSet = getField("ResultSet");

        Receiver r = null;

        if (_setting.isEnabledLogging()) {
            i.outLog(_statement);
        }

        // statementが未確保であるばあい、強制的にprepareStatementを呼び出します。
        i.addLine("if (_statement == null) {");
        i.addStatement("prepareStatement()");
        i.addLine("}");

        // resultSetがあいた状態であれば、先にcloseを行います。
        Statement expression = new Statement(_resultSet);
        expression.join("!=", new Statement(Value.NULL));
        i.openIf(expression);
        i.addStatement(new Receiver(_resultSet, "close"));
        i.assign(_resultSet, new Statement(Value.NULL));
        i.closeIf();

        r = new Receiver(_statement);
        r.call("executeQuery");
        i.assign(_resultSet, r);

    }
}