/*
 * 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.core.lang.collection;

import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * @param <K> the type of keys maintained by this map
 * @param <V> the type of mapped values
 */
public class ExpireMap<K, V> implements Map<K, V> {
	private Map<K, Long> kts;
	private Map<K, V> map;
	private int expire;

	public ExpireMap(Map<K, V> map, int expire) {
		this.map = map;
		this.expire = expire;
		this.kts = new HashMap<K, Long>();
	}

	/**
	 * @return the expire
	 */
	public int getExpire() {
		return expire;
	}

	/**
	 * @param expire the expire to set
	 */
	public void setExpire(int expire) {
		this.expire = expire;
	}

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

	public boolean containsKey(Object key) {
		if (map.containsKey(key)) {
			return true;
		}
		else {
			kts.remove(key);
			return false;
		}
	}

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

	public Set<java.util.Map.Entry<K, V>> entrySet() {
		return map.entrySet();
	}

	public V get(Object key) {
		Long t = kts.get(key);
		if (t != null) {
			if (System.currentTimeMillis() - t < expire) {
				return map.get(key);
			}
			else {
				kts.remove(key);
				map.remove(key);
			}
		}
		return null;
	}

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

	public Set<K> keySet() {
		return map.keySet();
	}

	public V put(K key, V value) {
		kts.put(key, System.currentTimeMillis());
		return map.put(key, value);
	}

	public void putAll(Map<? extends K, ? extends V> m) {
		for (Entry<? extends K, ? extends V> en : m.entrySet()) {
			put(en.getKey(), en.getValue());
		}
	}

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

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

	public Collection<V> values() {
		return map.values();
	}

	public boolean equals(Object o) {
		return map.equals(o);
	}

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

	public String toString() {
		return map.toString();
	}
}
