/*
 * $Id: FormPropertyConfig.java 471754 2006-11-06 14:55:09Z husted $
 *
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you 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.apache.struts.config;

import java.lang.reflect.Array;

import org.apache.commons.beanutils.ConvertUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * <p>A JavaBean representing the configuration information of a
 * <code>&lt;form-property&gt;</code> element in a Struts configuration
 * file.<p>
 *
 * @version $Rev: 471754 $ $Date: 2005-11-12 11:52:08 -0500 (Sat, 12 Nov 2005)$
 * @since Struts 1.1
 */
public class FormPropertyConfig extends BaseConfig {

    /** serialVersionUID */
    private static final long serialVersionUID = 4120657988013574721L;

    /**
     * The logging instance
     */
    private static final Log LOG = LogFactory.getLog(FormPropertyConfig.class);

    // ----------------------------------------------------- Instance Variables
    // ------------------------------------------------------------- Properties

    /**
     * String representation of the initial value for this property.
     */
    private String initial = null;

    /**
     * The JavaBean property name of the property described by this element.
     */
    private String name = null;

    /**
     * <p>The conditions under which the property described by this element
     * should be reset to its <code>initial</code> value when the form's
     * <code>reset</code> method is called.</p> <p>This may be set to true (to
     * always reset the property) or a comma-separated list of HTTP request
     * methods.</p>
     *
     * @since Struts 1.3
     */
    private String reset = null;

    /**
     * <p>The size of the array to be created if this property is an array
     * type and there is no specified <code>initial</code> value.  This value
     * must be non-negative.</p>
     *
     * @since Struts 1.1
     */
    private int size = 0;

    /**
     * The fully qualified Java class name of the implementation class of this
     * bean property, optionally followed by <code>[]</code> to indicate that
     * the property is indexed.
     */
    private String type = null;

    // ----------------------------------------------------------- Constructors

    /**
     * Standard no-arguments constructor for dynamic instantiation.
     */
    public FormPropertyConfig() {
        super();
    }

    /**
     * Constructor that preconfigures the relevant properties.
     *
     * @param val1 Name of this property
     * @param val2 Fully qualified class name of this property
     * @param val3 Initial value of this property (if any)
     */
    public FormPropertyConfig(final String val1, final String val2, final String val3) {
        this(val1, val2, val3, 0);
    }

    /**
     * Constructor that preconfigures the relevant properties.
     *
     * @param val1 Name of this property
     * @param val2 Fully qualified class name of this property
     * @param val3 Initial value of this property (if any)
     * @param val4 The conditions under which this property will be reset
     *                to its initial value.
     */
    public FormPropertyConfig(final String val1, final String val2, final String val3,
            final String val4) {
        this(val1, val2, val3, val4, 0);
    }

    /**
     * Constructor that preconfigures the relevant properties.
     *
     * @param val1 Name of this property
     * @param val2 Fully qualified class name of this property
     * @param val3 Initial value of this property (if any)
     * @param val4 Size of the array to be created if this property is an
     *                array with no defined initial value
     */
    public FormPropertyConfig(final String val1, final String val2, final String val3,
            final int val4) {
        this(val1, val2, val3, null, val4);
    }

    /**
     * Constructor that preconfigures the relevant properties.
     *
     * @param val1 Name of this property
     * @param val2 Fully qualified class name of this property
     * @param val3 Initial value of this property (if any)
     * @param val4 The conditions under which this property will be reset
     *                to its initial value.
     * @param val5 Size of the array to be created if this property is an
     *                array with no defined initial value
     */
    public FormPropertyConfig(final String val1, final String val2, final String val3,
            final String val4, final int val5) {
        super();
        setName(val1);
        setType(val2);
        setInitial(val3);
        setReset(val4);
        setSize(val5);
    }

    /**
     * @return Initial
     */
    public String getInitial() {
        return this.initial;
    }

    /**
     * @param val Initial
     */
    public void setInitial(final String val) {
        super.throwIfConfigured();

        this.initial = val;
    }

    /**
     * @return Name
     */
    public String getName() {
        return this.name;
    }

    /**
     * @param val Name
     */
    public void setName(final String val) {
        super.throwIfConfigured();

        this.name = val;
    }

    /**
     * @return Reset
     */
    public String getReset() {
        return this.reset;
    }

    /**
     * @param val Reset
     */
    public void setReset(final String val) {
        super.throwIfConfigured();

        this.reset = val;
    }

    /**
     * @return Size
     */
    public int getSize() {
        return this.size;
    }

    /**
     * @param val Size
     */
    public void setSize(final int val) {
        super.throwIfConfigured();

        if (val < 0) {
            throw new IllegalArgumentException("size < 0");
        }

        this.size = val;
    }

    /**
     * @return Type
     */
    public String getType() {
        return this.type;
    }

    /**
     * @param val Type
     */
    public void setType(final String val) {
        super.throwIfConfigured();

        this.type = val;
    }

    /**
     * Return a Class corresponds to the value specified for the
     * <code>type</code> property, taking into account the trailing "[]" for
     * arrays (as well as the ability to specify primitive Java types).
     * @return Class
     */
    public Class<?> getTypeClass() {
        // Identify the base class (in case an array was specified)
        String baseType = getType();
        boolean indexed = false;

        if (baseType.endsWith("[]")) {
            baseType = baseType.substring(0, baseType.length() - 2);
            indexed = true;
        }

        // Construct an appropriate Class instance for the base class
        final Class<?> baseClass;

        if ("boolean".equals(baseType)) {
            baseClass = Boolean.TYPE;
        } else if ("byte".equals(baseType)) {
            baseClass = Byte.TYPE;
        } else if ("char".equals(baseType)) {
            baseClass = Character.TYPE;
        } else if ("double".equals(baseType)) {
            baseClass = Double.TYPE;
        } else if ("float".equals(baseType)) {
            baseClass = Float.TYPE;
        } else if ("int".equals(baseType)) {
            baseClass = Integer.TYPE;
        } else if ("long".equals(baseType)) {
            baseClass = Long.TYPE;
        } else if ("short".equals(baseType)) {
            baseClass = Short.TYPE;
        } else {
            ClassLoader classLoader =
                Thread.currentThread().getContextClassLoader();

            if (classLoader == null) {
                classLoader = this.getClass().getClassLoader();
            }

            try {
                baseClass = classLoader.loadClass(baseType);
            } catch (final ClassNotFoundException ex) {
                LOG.warn(ex.getMessage());
                LOG.error("Class '" + baseType
                        + "' not found for property '" + this.name + "'");
                return null;
            }
        }

        // Return the base class or an array appropriately
        if (indexed) {
            return Array.newInstance(baseClass, 0).getClass();
        }
        return baseClass;

    }

    // --------------------------------------------------------- Public Methods

    /**
     * <p>Return an object representing the initial value of this property.
     * This is calculated according to the following algorithm:</p>
     *
     * <ul>
     *
     * <li>If the value you have specified for the <code>type</code> property
     * represents an array (i.e. it ends with "[]"):
     *
     * <ul>
     *
     * <li>If you have specified a value for the <code>initial</code>
     * property, <code>ConvertUtils.convert</code> will be called to convert
     * it into an instance of the specified array type.</li>
     *
     * <li>If you have not specified a value for the <code>initial</code>
     * property, an array of the length specified by the <code>size</code>
     * property will be created. Each element of the array will be
     * instantiated via the zero-args constructor on the specified class (if
     * any). Otherwise, <code>null</code> will be returned.</li>
     *
     * </ul></li>
     *
     * <li>If the value you have specified for the <code>type</code> property
     * does not represent an array:
     *
     * <ul>
     *
     * <li>If you have specified a value for the <code>initial</code>
     * property, <code>ConvertUtils.convert</code> will be called to convert
     * it into an object instance.</li>
     *
     * <li>If you have not specified a value for the <code>initial</code>
     * attribute, Struts will instantiate an instance via the zero-args
     * constructor on the specified class (if any). Otherwise,
     * <code>null</code> will be returned.</li>
     *
     * </ul></li>
     * </ul>
     * @return Object
     */
    public Object initial() {

        Object initialValue = null;

        Class<?> clazz = getTypeClass();
        if (clazz.isArray()) {
            if (this.initial != null) {
                initialValue = ConvertUtils.convert(this.initial, clazz);
            } else {
                initialValue =
                    Array.newInstance(clazz.getComponentType(), this.size);

                if (!(clazz.getComponentType().isPrimitive())) {
                    for (int i = 0; i < this.size; i++) {
                        try {
                            Array.set(initialValue, i,
                                clazz.getComponentType().getDeclaredConstructor().newInstance());
                        } catch (final ReflectiveOperationException e) {
                            LOG.warn(e.getMessage());
                            LOG.error("Unable to create instance of "
                                + clazz.getName() + " for property=" + this.name
                                + ", type=" + this.type + ", initial=" + this.initial
                                + ", size=" + this.size + ".");

                            //FIXME: Should we just dump the entire application/module ?
                        }
                    }
                }
            }
        } else {
            if (this.initial != null) {
                initialValue = ConvertUtils.convert(this.initial, clazz);
            } else {
                try {
                    initialValue = clazz.getDeclaredConstructor().newInstance();
                } catch (final ReflectiveOperationException e) {
                    LOG.warn(e.getMessage());
                }
            }
        }

        return initialValue;
    }

    /** <p>Inherit values that have not been overridden from the provided
     * config object.  Subclasses overriding this method should verify that
     * the given parameter is of a class that contains a property it is trying
     * to inherit:</p>
     * <pre>
     * if (config instanceof MyCustomFormPropertyConfig) {
     *     MyCustomFormPropertyConfig myConfig =
     *         (MyCustomFormPropertyConfig) config;
     *
     *     if (getMyCustomProp() == null) {
     *         setMyCustomProp(myConfig.getMyCustomProp());
     *     }
     * }
     * </pre>
     * @param config The object that this instance will be inheriting its
     *               values from.
     */
    public void inheritFrom(final FormPropertyConfig config) {

        super.throwIfConfigured();

        if (getInitial() == null) {
            setInitial(config.getInitial());
        }

        if (getName() == null) {
            setName(config.getName());
        }

        if (getSize() == 0) {
            setSize(config.getSize());
        }

        if (getType() == null) {
            setType(config.getType());
        }

        inheritProperties(config);
    }

    /**
     * Return a String representation of this object.
     */
    @Override
    public String toString() {
        final String sb = "FormPropertyConfig["
                + "name=" + this.name
                + ",type=" + this.type
                + ",initial=" + this.initial
                + ",reset=" + this.reset
                + "]";
        return sb;
    }
}
