/*
 * blancoIg
 * 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.struts.expander.form;

import blanco.ig.expander.Type;
import blanco.ig.expander.Value;
import blanco.ig.expander.implementor.Call;
import blanco.ig.expander.implementor.Cast;
import blanco.ig.expander.implementor.Receiver;
import blanco.ig.expander.implementor.Statement;
import blanco.ig.expander.method.MethodExpander;
import blanco.struts.expander.StrutsImplementor;

/**
 * @author Yasuo Nakanishi
 */
public class GetListItemMethod extends MethodExpander {

    private String _name = "";

    private Type _itemType = null;

    private Value _indexArgument = null;

    public GetListItemMethod(String name, Type itemType) {
        super(createName("get", name));
        _name = name;
        _itemType = getNameAdjuster().adjust(itemType);
    }

    public void setupSignature() {
        setReturnType(_itemType);

        _indexArgument = new Value(int.class, "index");
        addArgument(_indexArgument);

        String doc = "";

        doc = "リストのアイテムを取得。";
        getJavaDoc().addLine(doc);

        getJavaDoc().addParameter(_indexArgument.getName(), "取得するアイテムのインデックス。");
    }

    public void implement() {

        StrutsImplementor si = new StrutsImplementor(getData());
        Receiver r = null;
        Call call = null;

        Value listField = getField(_name + "List");

        Receiver left = new Receiver(_indexArgument);
        left.join("+", new Statement(int.class, "1"));

        Receiver right = new Receiver(listField, "size");
        left.join(">=", right);

        si.openWhile(left);
        r = new Receiver(listField);
        call = r.call("add");
        call.addArgument(new Call(_itemType));
        si.addStatement(r);
        si.closeWhile();

        Cast cast = new Cast(_itemType);
        r = cast.value(listField);
        call = r.call("get");
        call.addArgument(_indexArgument);
        si.addReturn(cast);
    }
}
