/*
 * 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.xwork2;

import java.util.Map;

import nuts.exts.xwork2.util.ContextUtils;


/**
 * SessionStateProvider
 */
public class SessionStateProvider implements StateProvider {
	private String prefix;
	
	/**
	 * Constructor
	 */
	public SessionStateProvider() {
		this(null);
	}
	
	/**
	 * Constructor
	 * @param prefix prefix
	 */
	public SessionStateProvider(String prefix) {
		this.prefix = prefix;
	}
	
	/**
	 * @return the prefix
	 */
	public String getPrefix() {
		return prefix;
	}

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

	/**
	 * get key name
	 * @param name state name
	 * @return key name
	 */
	private String getKey(String name) {
		return prefix == null ? name : prefix + name;
	}

	/**
	 * @return session
	 */
	private Map<String, Object> getSession() {
		return ContextUtils.getSession();
	}
	
	/**
	 * Save state
	 * @param name state name
	 * @param value state value
	 */
	public void saveState(String name, Object value) {
		getSession().put(getKey(name), value);
	}
	
	/**
	 * Load state
	 * @param name state name
	 * @return state value 
	 */
	public Object loadState(String name) {
		return getSession().get(getKey(name));
	}
}
