/**
 * License Agreement.
 *
 * Rich Faces - Natural Ajax for Java Server Faces (JSF)
 *
 * Copyright (C) 2007 Exadel, Inc.
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License version 2.1 as published by the Free Software Foundation.
 *
 * This library 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
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301  USA
 */

package org.ajax4jsf.cache;

import java.util.AbstractMap;
import java.util.AbstractSet;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

import javax.servlet.ServletContext;

/**
 * @author Nick Belaevski - nbelaevski@exadel.com
 * created 02.05.2007
 * 
 */
public class ServletContextInitMap extends AbstractMap {
	private ServletContext servletContext;
	
	public ServletContextInitMap(ServletContext servletContext) {
		super();
		this.servletContext = servletContext;
	}

	public Set entrySet() {
		return new AbstractSet() {

			public Iterator iterator() {
				return new Iterator() {
					private Enumeration initNames = servletContext.getInitParameterNames();
					
					public boolean hasNext() {
						return initNames.hasMoreElements();
					}

					public Object next() {
						String key = (String) initNames.nextElement();
						String value = servletContext.getInitParameter(key);
					
						return new ServletContextInitMapEntry(key, value);
					}

					public void remove() {
						throw new UnsupportedOperationException();
					}
				
				};
			}

			public int size() {
				int result = 0;
				Enumeration initNames = servletContext.getInitParameterNames();
				while (initNames.hasMoreElements()) {
					result++;
				}

				return result;
			}
			
			public boolean isEmpty() {
				return !servletContext.getInitParameterNames().hasMoreElements();
			}
		};
	}

}

class ServletContextInitMapEntry implements Map.Entry {

	private Object key;
	private Object value;
	
	public ServletContextInitMapEntry(Object key, Object value) {
		super();
		this.key = key;
		this.value = value;
	}

	public ServletContextInitMapEntry(Object key) {
		super();
		this.key = key;
	}

	public Object getKey() {
		return key;
	}

	public Object getValue() {
		return value;
	}

	public Object setValue(Object value) {
		Object oldValue = this.value;
		this.value = value;
		return oldValue;
	}
	
}