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

import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.HashMap;
import java.util.Map;

import woolpack.utils.MapBuilder;

abstract class AbstractNumberConverter {
	
	AbstractNumberConverter() {
	}

	private static final Map<Class, AbstractNumberConverter>
	MAP = MapBuilder.get(
			new HashMap<Class, AbstractNumberConverter>()).put(Byte.class,
			new AbstractNumberConverter() {
				Number convertLocal(final Number old) {
					return Byte.valueOf(old.byteValue());
				}
			}).put(Short.class, new AbstractNumberConverter() {
		Number convertLocal(final Number old) {
			return Short.valueOf(old.shortValue());
		}
	}).put(Integer.class, new AbstractNumberConverter() {
		Number convertLocal(final Number old) {
			return Integer.valueOf(old.intValue());
		}
	}).put(Long.class, new AbstractNumberConverter() {
		Number convertLocal(final Number old) {
			return Long.valueOf(old.longValue());
		}
	}).put(Float.class, new AbstractNumberConverter() {
		Number convertLocal(final Number old) {
			return Float.valueOf(old.floatValue());
		}
	}).put(Double.class, new AbstractNumberConverter() {
		Number convertLocal(final Number old) {
			return Double.valueOf(old.doubleValue());
		}
	}).put(BigInteger.class, new AbstractNumberConverter() {
		Number convertLocal(final Number old) {
			return BigInteger.valueOf(old.longValue());
		}
	}).put(BigDecimal.class, new AbstractNumberConverter() {
		Number convertLocal(final Number old) {
			return new BigDecimal(old.doubleValue());
		}
	}).get();

	abstract Number convertLocal(Number old);

	static Number convert(final Number old, final Class toType) {
		if (toType.equals(old.getClass())) {
			return old;
		}
		return MAP.get(toType).convertLocal(old);
	}
}
