/*
 * Copyright 2012 s_wolff.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.aegee.runanddine.util.forms;

import java.io.Serializable;

/**
 * This class provides sophisticated means for text fields. It automatically
 * adds type validators to the text field to force input that can be saved to
 * the specified model.
 *
 * @author s_wolff
 * @see AbstractFormField
 * @see org.apache.wicket.markup.html.form.TextField
 */
public class TextField<T extends Serializable> extends AbstractFormField<T> {

    /**
     * Create a new text field for text input. A validator is added
     * automatically to ensure that the provided input can be saved in the given
     * object after the form was sumitted successfully.
     *
     * @param id the component markup id
     * @param obj the object that backens the form field
     * @param fieldName the field name of the object that backens the form field
     * @param labelText the label text that shall be displayed for this field
     * @param required whether this field is required or optional
     */
    public TextField(String id, T obj, String fieldName, String labelText, boolean required) {
        super(id, obj, new org.apache.wicket.markup.html.form.TextField(AbstractFormField.ID_INPUT, getFieldType(obj, fieldName)), fieldName, labelText, required);
    }

    /**
     * Gets the type of the field with the given name of the given object.<br>
     * <br> Note that this method will never throw an exception! Any exception
     * will be caught and
     * <code>Object.class</code> will be returned.
     *
     * @param <T>
     * @param obj the objects that contains a field thats type is of interest
     * @param fieldName the name of the field
     * @return a
     * <code>Class</code> instance representing the type of the field
     */
    public static <T extends Serializable> Class getFieldType(T obj, String fieldName) {
        try {
            return obj.getClass().getDeclaredField(fieldName).getType();
        } catch (Exception e) {
            // Checked exceptions that may occure: NoSuchFieldException, SecurityException
            return Object.class;
        }
    }
}
