/*
 * This file is part of Nuts Framework.
 * Copyright(C) 2009-2012 Nuts Develop Team.
 *
 * Nuts Framework is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License any later version.
 *
 * Nuts Framework is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.	 See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with Nuts Framework. If not, see <http://www.gnu.org/licenses/>.
 */
package nuts.exts.struts2.components;

import java.lang.reflect.Array;
import java.util.Collection;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.util.ContainUtil;
import org.apache.struts2.util.MakeIterator;
import org.apache.struts2.views.annotations.StrutsTagAttribute;

import com.opensymphony.xwork2.util.ValueStack;

/**
 * ListUIBean is the standard superclass of all Nuts Struts list handling components.
 *
 * <p/>
 *
 * <!-- START SNIPPET: javadoc -->
 *
 * Note that the listkey and listvalue attribute will default to "key" and "value"
 * respectively only when the list attribute is evaluated to a Map or its decendant.
 * Everything else will result in listkey and listvalue to be null and not used.
 *
 * <!-- END SNIPPET: javadoc -->
 *
 */
public abstract class ListUIBean extends UIBean {
    protected Object list;
    protected String listKey;
    protected String listValue;

    // indicate if an exception is to be thrown when value attribute is null
    protected boolean throwExceptionOnNullValueAttribute = false;

    protected ListUIBean(ValueStack stack, HttpServletRequest request, HttpServletResponse response) {
        super(stack, request, response);
    }

    protected void evaluateExtraParams() {
        Object value = null;

        if (list == null) {
            list = parameters.get("list");
        }

		if (list instanceof String) {
			value = findValue((String)list);
		}
		else if (list instanceof Collection) {
			value = list;
		}
		else if (list instanceof Map) {
			value = list;
		}
		else if (MakeIterator.isIterable(list)) {
			value = MakeIterator.convert(list);
		}

		if (value == null) {
            if (throwExceptionOnNullValueAttribute) {
                // will throw an exception if not found
                value = findValue((list == null) ? (String) list : list.toString(), "list",
                    "The requested list key '" + list + "' could not be resolved as a collection/array/map/enumeration/iterator type. " +
                    "Example: people or people.{name}");
            }
            else {
                // ww-1010, allows value with null value to be compatible with ww
                // 2.1.7 behaviour
				value = findValue((list == null) ? (String)list : list.toString());
            }
        }

		if (value instanceof Collection) {
			addParameter("list", value);
		}
		else {
			addParameter("list", MakeIterator.convert(value));
		}

		if (value instanceof Collection) {
			addParameter("listSize", Integer.valueOf(((Collection)value).size()));
		}
		else if (value instanceof Map) {
			addParameter("listSize", Integer.valueOf(((Map)value).size()));
		}
		else if (value != null && value.getClass().isArray()) {
			addParameter("listSize", Integer.valueOf(Array.getLength(value)));
		}

		if (listKey != null) {
			listKey = stripExpressionIfAltSyntax(listKey);
			addParameter("listKey", listKey);
		}
		else if (value instanceof Map) {
			addParameter("listKey", "key");
		}

		if (listValue != null) {
			listValue = stripExpressionIfAltSyntax(listValue);
			addParameter("listValue", listValue);
		}
		else if (value instanceof Map) {
			addParameter("listValue", "value");
		}
    }

    public boolean contains(Object obj1, Object obj2) {
        return ContainUtil.contains(obj1, obj2);
    }

    protected Class getValueClassType() {
        return null; // don't convert nameValue to anything, we need the raw value
    }

    @StrutsTagAttribute(description="Iterable source to populate from. If the list is a Map (key, value), the Map key will become the option 'value'" +
                " parameter and the Map value will become the option body.", required=true)
    public void setList(Object list) {
        this.list = list;
    }

    @StrutsTagAttribute(description=" Property of list objects to get field value from")
    public void setListKey(String listKey) {
        this.listKey = listKey;
    }

    @StrutsTagAttribute(description="Property of list objects to get field content from")
    public void setListValue(String listValue) {
        this.listValue = listValue;
    }


    public void setThrowExceptionOnNullValueAttribute(boolean throwExceptionOnNullValueAttribute) {
        this.throwExceptionOnNullValueAttribute = throwExceptionOnNullValueAttribute;
    }
}
