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