/*
 * 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.AbstractMap;
import java.util.AbstractSet;
import java.util.Iterator;
import java.util.Set;

/**
 * キーの{@link Iterator}を用いる{@link Map}をスケルトン実装。
 * @author nakamura
 *
 */
abstract public class KeyIteratorMap<K,V> extends AbstractMap<K,V> {
	
	/**
	 * {@link #entrySet()}から呼び出される(called)。
	 * キーの{@link Iterator}を返す。
	 * @return キーの{@link Iterator}。
	 */
	abstract protected Iterator<K> getKeyIterator();
	
	/**
	 * {@link #entrySet()}から呼び出される(called)。
	 * キーに対応する値を返す。
	 * @param key キー。
	 * @return 値。
	 */
	abstract protected V getValue(Object key);
	
	@Override public Set<Entry<K,V>> entrySet() {
		return  new AbstractSet<Entry<K,V>>(){
			public int size() {
				int i=0;
				for(final Iterator it = iterator();it.hasNext();){
					it.next();
					i++;
				}
				return i;
			}
			public Iterator<Entry<K,V>> iterator() {
				final Iterator<K> it = getKeyIterator();
				return new Iterator<Entry<K,V>>(){
					public void remove() {
						it.remove();
					}
					public boolean hasNext() {
						return it.hasNext();
					}
					public Entry<K,V> next() {
						final K key = it.next();
						return new Entry<K,V>(){
							public K getKey() {
								return key;
							}
							public V getValue() {
								return KeyIteratorMap.this.getValue(key);
							}
							public V setValue(final V value) {
								return KeyIteratorMap.this.put(key, value);
							}
//							public boolean equals(final Object o){
//								if(o instanceof Entry){
//									final Entry e1 = this;
//									final Entry e2 = (Entry)o;
//									return (e1.getKey()==null ?
//										      e2.getKey()==null : e1.getKey().equals(e2.getKey()))  &&
//										      (e1.getValue()==null ?
//										       e2.getValue()==null : e1.getValue().equals(e2.getValue()));
//								}
//								return false;
//							}
//							public int hashCode(){
//								return (this.getKey()==null   ? 0 : this.getKey().hashCode()) ^
//							     (this.getValue()==null ? 0 : this.getValue().hashCode());
//							}
						};
					}							
				};
			}
		};
	}
}
