/*
 * 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 KeyIteratorMap<K,V> {
	
	private final Iterable<Map<K,V>> iterable;
	
	/**
	 * コンストラクタ。
	 * @param iterable {@link Map}の一覧。本クラスはこの引数の{@link Map}の状態を変化させる。
	 * @throws NullPointerException 引数が null の場合。
	 */
	public MapIterableMap(final Iterable<Map<K,V>> iterable){
		iterable.getClass();
		this.iterable = iterable;
	}

	@Override protected Iterator<K> getKeyIterator() {
		int tmp = 0;
		for(final Map<K,V> m:iterable){
			tmp += m.size();
		}
		final Set<K> set = new HashSet<K>(tmp);
		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 getValue(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;
	}
}
