/*
 * This file is part of Nuts Framework.
 * Copyright (C) 2009 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.actions;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Map.Entry;

import nuts.core.lang.StringUtils;
import nuts.core.util.CodeText;
import nuts.exts.xwork2.util.ContextUtils;

import com.opensymphony.xwork2.util.ValueStack;

/**
 */
@SuppressWarnings("serial")
public class CodeMapAction extends CommonAction {

	private String exp;
	private List<CodeText> data;

	/**
	 * @return the exp
	 */
	public String getExp() {
		return exp;
	}

	/**
	 * @param exp the exp to set
	 */
	public void setExp(String exp) {
		this.exp = exp;
	}

	/**
	 * @return the data
	 */
	public List<CodeText> getData() {
		return data;
	}

	/**
	 * @param data the data to set
	 */
	public void setData(List<CodeText> data) {
		this.data = data;
	}

	/**
	 * execute
	 * @return SUCCESS
	 * @throws Exception if an error occurs
	 */
	@SuppressWarnings("unchecked")
	public String execute() throws Exception {
		if (StringUtils.isNotBlank(exp)) {
			ValueStack vs = ContextUtils.getValueStack();
			Object value = vs.findValue(exp);
			if (value instanceof Map) {
				data = new ArrayList<CodeText>();
				Set<Entry> s = ((Map)value).entrySet();
				for (Entry e : s) {
					data.add(new CodeText(String.valueOf(e.getKey()), String.valueOf(e.getValue())));
				}
			}
			else if (value instanceof Collection) {
				data = new ArrayList<CodeText>();
				for (Object o : ((Collection)value)) {
					data.add(new CodeText(String.valueOf(o), String.valueOf(o)));
				}
			}
		}
		return SUCCESS;
	}
}
