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

import nuts.core.lang.Strings;

import java.util.HashMap;
import java.util.Map;


public class CommonMultiWorkAction extends CommonSyncWorkAction {
	protected String key;

	/**
	 * @return the key
	 */
	public String getKey() {
		return key;
	}

	/**
	 * @param key the key to set
	 */
	public void setKey(String key) {
		this.key = Strings.stripToNull(key);
	}

	protected Map getActionMap(boolean create) {
		Map m = (Map)getApplication().get(getClass().getName());
		if (m == null && create) {
			m = new HashMap();
			getApplication().put(getClass().getName(), m);
		}
		return m;
	}
	
	/**
	 * get singleton instance
	 * @return instance
	 */
	@Override
	protected CommonSyncWorkAction getInstance() {
		Map m = getActionMap(false);
		if (m == null) {
			return this;
		}
	
		CommonSyncWorkAction a = (CommonSyncWorkAction)m.get(key);
		return a == null ? this : a;
	}

	/**
	 * set singleton instance
	 * @param instance instance
	 */
	@Override
	@SuppressWarnings("unchecked")
	protected void setInstance(CommonSyncWorkAction instance) {
		if (instance == null) {
			Map m = getActionMap(false);
			if (m != null) {
				m.remove(key);
			}
		}
		else {
			Map m = getActionMap(true);
			m.put(key, instance);
		}
	}
}
