/*
 * Copyright 2006 Takahiro Nakamura.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
 * either express or implied. See the License for the specific language
 * governing permissions and limitations under the License.
 */
package woolpack.utils;

import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

/**
 * {@link Map}の一覧を重ねた{@link Map}です。
 * 
 * @author nakamura
 * 
 */
public class MapIterableMap<K, V> extends AbstractKeyIteratorMap<K, V> {
	private Iterable<Map<K, V>> iterable;

	/**
	 * @param iterable {@link Map}の一覧。
	 */
	public MapIterableMap(final Iterable<Map<K, V>> iterable) {
		super();
		this.iterable = iterable;
	}

	@Override
	protected Iterator<K> getKeyIterator() {
		final Set<K> set = new HashSet<K>();
		for (final Map<K, V> m : iterable) {
			set.addAll(m.keySet());
		}
		final Iterator<K> it = set.iterator();
		return new Iterator<K>() {
			private K key;

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

			public boolean hasNext() {
				return it.hasNext();
			}

			public K next() {
				key = it.next();
				return key;
			}
		};
	}

	@Override
	protected V getValue(final Object key) {
		for (final Map<K, V> m : iterable) {
			final V val = m.get(key);
			if (val != null) {
				return val;
			}
		}
		return null;
	}

	/**
	 * {@link Map}の一覧から各{@link Map}を検索し始めに見つかったキーの値を返します。
	 */
	@Override
	public V get(final Object key) {
		return super.get(key);
	}

	/**
	 * {@link Map}の一覧の先頭の{@link Map}に対して{@link Map#put(Object, Object)}を実行します。
	 */
	@Override
	public V put(final K key, final V val) {
		for (final Map<K, V> m : iterable) {
			return m.put(key, val);
		}
		return null;
	}

	public Iterable<Map<K, V>> getIterable() {
		return iterable;
	}

	public void setIterable(final Iterable<Map<K, V>> iterable) {
		this.iterable = iterable;
	}
}
