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

import blanco.db.definition.QueryIteratorDotNet;
import blanco.db.util.BlancoDbObjectStorageDotNet;
import blanco.ig.expander.IgType;
import blanco.ig.expander.implementor.Implementor;
import blanco.ig.expander.method.MethodExpander;

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

    private String runtimePackage = null;

    public ExecuteQueryMethodDotNet(final BlancoDbObjectStorageDotNet storage,
            final QueryIteratorDotNet iterator) {
        super("ExecuteQuery");
        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("検索型クエリを実行します。");

        addUsingType(new IgType("System.Data.CommandBehavior"));
    }

    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("");
        }

        implementor.addLine("if (fStatement == null) {");
        implementor.addLine("PrepareStatement();");
        implementor.addLine("}");
        implementor.addLine("if (fResultSet != null) {");
        implementor.addLine("fResultSet.Close();");
        implementor.addLine("fResultSet = null;");
        implementor.addLine("}");
        implementor.addLine("try {");
        implementor
                .addLine("fResultSet = fStatement.ExecuteReader(CommandBehavior.SequentialAccess);");
        implementor.addLine("} catch (SqlException ex) {");
        implementor.addLine("throw BlancoDbUtil.ConvertToBlancoException(ex);");
        implementor.addLine("}");
    }
}