/*
 * 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.Map;

class SimilarPropertyNameMap<V> extends DelegationMap<String, V> {
	private static final int INDEX_JAVA_LOWER = 1;
	private static final int INDEX_JAVA_UPPER = 2;
	private static final int INDEX_SQL_LOWER = 4;
	private static final int INDEX_SQL_UPPER = 3;
	private static final int SIMILAR_COUNT = 5;

	SimilarPropertyNameMap(final Map<String, V> child) {
		super(child);
	}

	@Override
	public boolean containsKey(final Object arg0) {
		final Object[] keys = getKeys(arg0);
		for (int i = 0; i < keys.length; i++) {
			final Object key = keys[i];
			if (super.containsKey(key)) {
				return true;
			}
		}
		return false;
	}

	@Override
	public V get(final Object arg0) {
		final Object[] keys = getKeys(arg0);
		for (int i = 0; i < keys.length; i++) {
			final Object key = keys[i];
			final V value = super.get(key);
			if (value != null) {
				return value;
			}
		}
		return null;
	}

	private Object[] getKeys(final Object key) {
		final Object[] keys = new String[SIMILAR_COUNT];
		keys[0] = key;
		String s = key.toString();
		s = PropertyUtils.toJavaName(s);
		keys[INDEX_JAVA_LOWER] = s;
		s = Character.toUpperCase(s.charAt(0)) + s.substring(1);
		keys[INDEX_JAVA_UPPER] = s;
		s = PropertyUtils.toSQLName(s);
		keys[INDEX_SQL_UPPER] = s;
		s = s.toLowerCase();
		keys[INDEX_SQL_LOWER] = s;
		return keys;
	}
}
