/*
 * 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.method.MethodExpander;
import blanco.struts.definition.form.Form;
import blanco.struts.expander.TypeFactory;

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

    private Form _definition = null;

    private TypeFactory _typeFactory = null;

    private Value _mappintArgument = null;

    private Value _requestArgument = null;

    public ValidateMethod(Form definition, TypeFactory typeFactory) {
        super("validate");
        _definition = definition;
        _typeFactory = typeFactory;
    }

    public void setupSignature() {
        _mappintArgument = new Value(new Type(
                "org.apache.struts.action.ActionMapping"), "mapping");
        _requestArgument = new Value(new Type(
                "javax.servlet.http.HttpServletRequest"), "request");

        addArgument(_mappintArgument);
        addArgument(_requestArgument);

        setReturnType(new Type("org.apache.struts.action.ActionErrors"));

        String doc = "";

        doc = "validateメソッド。";
        getJavaDoc().addLine(doc);

        doc = "このメソッドはStrutsにより呼ばれます。";
        getJavaDoc().addLine(doc);

        String name = "";
        name = _mappintArgument.getName();
        getJavaDoc().addParameter(name, name + " パラメータ。");

        name = _requestArgument.getName();
        getJavaDoc().addParameter(name, name + " パラメータ。");

        doc = "エラーがなかった場合、空のActionErrosが返されます。";
        getJavaDoc().addReturn(doc);
    }

    public void implement() {
        addUsingType(new Type("org.apache.struts.action.ActionErrors"));
        getData().addLine("ActionErrors errors = new ActionErrors();");

        if (_definition.isAutoValidation()) {
            getData().addLine("errors = validateRequired(mapping, request);");
            getData().addLine("if (!errors.isEmpty()) {");
            getData().addLine("return errors;");
            getData().addLine("}");

            getData().addLine("errors = validateFormat(mapping, request);");
            getData().addLine("if (!errors.isEmpty()) {");
            getData().addLine("return errors;");
            getData().addLine("}");

            getData().addLine("errors = validateRange(mapping, request);");
        }
        getData().addLine("return errors;");
    }

}
