/*
 * blanco Framework
 * Copyright (C) 2004-2005 IGA Tosiki
 * 
 * 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.caller;

import blanco.db.util.BlancoDbObjectStorageDotNet;
import blanco.ig.expander.IgType;
import blanco.ig.expander.method.MethodExpander;

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

    private String runtimePackage = null;

    public ExecuteMethodDotNet(final BlancoDbObjectStorageDotNet storage) {
        super("Execute");
        this.storage = storage;

        runtimePackage = storage.getSetting().getRootNameSpace();
        if (storage.getSetting().getRuntimePackage() != null) {
            runtimePackage = storage.getSetting().getRuntimePackage();
        }

        final IgType blancoDbUtil = new IgType(runtimePackage
                + ".util.BlancoDbUtil");
        addUsingType(blancoDbUtil);
    }

    public void setupSignature() {
        getJavaDoc().addLine("ストアドプロシージャを実行します。");
    }

    public void implement() {
        if (storage.getSetting().isLogging()) {
            getData().addLine("if (fLog.isDebugEnabled()) {");
            getData().addLine("fLog.debug(\"" + getName() + "\");");
            getData().addLine("}");
            getData().addLine("");
        }

        // statementが未確保であるばあい、強制的にprepareStatementを呼び出します。
        getData().addLine("if (fStatement == null) {");
        getData()
                .addLine(
                        "// SqlCommandが未取得の状態なので、ExecuteNonQuery()実行に先立ちPrepareCall()メソッドを呼び出して取得します。");
        getData().addLine("PrepareCall();");
        getData().addLine("}");

        getData().addLine("");

        // べったりと展開します。
        getData().addLine("try {");
        getData().addLine("fStatement.ExecuteNonQuery();");
        getData().addLine("} catch (SqlException ex) {");
        getData().addLine("throw BlancoDbUtil.ConvertToBlancoException(ex);");
        getData().addLine("}");
    }
}