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

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

import woolpack.utils.BuildableHashMap;

abstract class AbstractNumberConverter {
	
	private AbstractNumberConverter() {
	}

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

	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);
	}
}
