package com.sptg.repeater.dh;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

@SuppressWarnings("rawtypes")
public class PageData extends HashMap implements Map {
	HttpServletRequest request;
	Map map = null;
	private static final long serialVersionUID = 1L;

	@SuppressWarnings("unchecked")
	public PageData(HttpServletRequest request) {
		this.request = request;
		Map properties = request.getParameterMap();
		Map returnMap = new HashMap();
		Iterator entries = properties.entrySet().iterator();
		Entry entry;
		String name = "";
		String value = "";
		while (entries.hasNext()) {
			entry = (Entry) entries.next();
			name = (String) entry.getKey();
			Object valueObj = entry.getValue();
			if (null == valueObj) {
				value = "";
			} else if (valueObj instanceof String[]) {
				String[] values = (String[]) valueObj;
				for (int i = 0; i < values.length; i++) {
					value += values[i] + ",";
				}
				value = value.substring(0, value.length() - 1);
			} else {
				value = valueObj.toString();
			}
			returnMap.put(name, value);
			value = "";
		}
		map = returnMap;
	}

	public PageData() {
		map = new HashMap();
	}

	public Object get(Object key) {
		Object obj = null;
		if (map.get(key) instanceof Object[]) {
			Object[] arr = (Object[]) map.get(key);
			obj = request == null ? arr : (request.getParameter((String) key) == null ? arr : arr[0]);
		}else{
			obj = map.get(key);
		}
		return obj;
	}

	@SuppressWarnings("unchecked")
	public Object put(Object key, Object value) {
		return map.put(key, value);
	}

	public Object remove(Object key) {
		return map.remove(key);
	}

	public void clear() {
		map.clear();
	}

	public boolean containsKey(Object key) {
		return map.containsKey(key);
	}

	public boolean containsValue(Object key) {
		return map.containsValue(key);
	}

	public Set entrySet() {
		return map.entrySet();
	}

	public boolean isEmpty() {
		return map.isEmpty();
	}

	public Set keySet() {
		return map.keySet();
	}

	@SuppressWarnings("unchecked")
	public void putAll(Map a) {
		map.putAll(a);
	}

	public int size() {
		return map.size();
	}

	public Collection values() {
		return map.values();
	}

	// -------------

	public String getString(Object a) {
		return (String) get(a);
	}
}
