/*
 * 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.HashMap;
import java.util.HashSet;
import java.util.Map;

class InjectiveMap<K, V> extends DelegationMap<K, V> {
	private final Map<K, V> map;

	InjectiveMap(final Map<K, V> map) {
		super(map);
		this.map = map;
		check(map);
	}

	private static <K, V> void check(final Map<K, V> m) {
		if (m.values().size() != new HashSet<V>(m.values()).size()) {
			throw new IllegalStateException("value duplicate");
		}
	}

	private boolean check(final K key, final V value) {
		return !super.containsValue(value)
				|| ((value == null) ? (super.get(key) == null) : (value
						.equals(super.get(key))));
	}

	@Override
	public V put(final K key, final V value) {
		if (!check(key, value)) {
			throw new IllegalStateException("value duplicate:" + value);
		}
		return super.put(key, value);
	}

	@Override
	public void putAll(final Map<? extends K, ? extends V> t) {
		for (final Entry<? extends K, ? extends V> entry : t.entrySet()) {
			//final V value = t.get(key);
			if (!check(entry.getKey(), entry.getValue())) {
				final Map<K, V> tmpMap = new HashMap<K, V>(map);
				tmpMap.putAll(t);
				check(tmpMap);
				break;
			}
		}
		super.putAll(t);
	}
}
