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

import blanco.db.definition.QueryIterator;
import blanco.db.properties.GenerationProperties;
import blanco.db.util.BlancoDbObjectStorage;
import blanco.ig.expander.Type;
import blanco.ig.expander.Value;
import blanco.ig.expander.implementor.Call;
import blanco.ig.expander.implementor.Implementor;
import blanco.ig.expander.implementor.Receiver;
import blanco.ig.expander.method.MethodExpander;

/**
 * @author Yasuo Nakanishi
 */
public class GetAsListMethod extends MethodExpander {
    private GenerationProperties _properties = null;

    private QueryIterator _iterator = null;

    public GetAsListMethod(QueryIterator iterator) {
        super("getAsList");
        _iterator = iterator;
        _properties = BlancoDbObjectStorage.getInstance()
                .getGenerationProperties();
    }

    public void setupSignature() {
        setReturnType(new Type(List.class));
        addException(SQLException.class);

        if (_properties.isGenerateJavaDoc()) {
            getJavaDoc().addLine("検索結果をリストで取得します。<br>");
            getJavaDoc()
                    .addLine("リストには " + _iterator.getName() + "クラスが格納されます。");
            getJavaDoc().addLine("なるべくgetListを優先して利用してください");
            getJavaDoc().addReturn(
                    _iterator.getName() + "クラスのList。検索結果が0件の場合には空のリスト。");
        }
    }

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

        Value result = new Value(List.class, "result");
        i.declare(result, new Call(ArrayList.class));

        i.openWhile("next()");

        Receiver r = new Receiver(result);
        Call c = r.call("add");
        c.addArgument(new Call("getRow"));
        i.addStatement(r);

        i.closeWhile();

        i.addReturn(result);
    }

}