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

import java.sql.PreparedStatement;

import blanco.commons.util.BlancoNameAdjuster;
import blanco.db.util.BlancoDbObjectStorage;
import blanco.ig.expander.Type;
import blanco.ig.expander.Value;
import blanco.ig.expander.implementor.Implementor;
import blanco.ig.expander.implementor.Receiver;
import blanco.ig.expander.implementor.Statement;
import blanco.ig.expander.method.MethodExpander;

/**
 * @author Yasuo Nakanishi
 */
public class CloseMethod extends MethodExpander {
    private BlancoDbObjectStorage storage = null;

    private Value _statement = null;

    public CloseMethod(final BlancoDbObjectStorage storage) {
        super("close");
        this.storage = storage;

        _statement = new Value(PreparedStatement.class, BlancoNameAdjuster
                .toParameterName("fStatement"));
    }

    public void setupSignature() {
        getJavaDoc().addException(new Type("java.sql.SQLException"),
                "SQL例外が発生した場合。");
        addException(new Type("java.sql.SQLException"));

        getJavaDoc().addLine("このクラスのクローズ処理をおこないます。");
        getJavaDoc().addLine("");
        getJavaDoc().addLine(
                "内部的に生成していたJDBCリソースのオブジェクトに対して close()メソッドの呼び出しをおこないます。<br>");
        getJavaDoc().addLine("クラスの利用が終わったら、必ずこのメソッドを呼び出すようにします。");
    }

    public void implement() {
        final Implementor implementor = new Implementor(getData());

        if (storage.getSetting().isLogging()) {
            implementor.addLine("if (fLog.isDebugEnabled()) {");
            implementor.addLine("fLog.debug(\"" + getName() + "\");");
            implementor.addLine("}");
            implementor.addLine("");
        }

        Receiver r = null;

        Statement s = new Statement(_statement);
        s.join("!=", new Statement(Value.NULL));
        implementor.openIf(s);
        r = new Receiver(_statement);
        r.call("close");
        implementor.addStatement(r);
        implementor.assign(_statement, new Statement(Value.NULL));
        implementor.closeIf();
    }

}