/*
 * This file is part of Nuts Framework.
 * Copyright(C) 2009-2012 Nuts Develop Team.
 *
 * Nuts Framework is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License any later version.
 * 
 * Nuts Framework is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with Nuts Framework. If not, see <http://www.gnu.org/licenses/>.
 */
package nuts.core.castor.castors;

import nuts.core.castor.AbstractCastor;
import nuts.core.castor.CastContext;
import nuts.core.lang.Numbers;

import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.Calendar;
import java.util.Date;

public class NumberTypeCastor {
	public static class NumberCastor extends AbstractCastor<Object, Number> {
		public NumberCastor() {
			super(Object.class, Number.class);
		}

		@Override
		protected Number convertValue(Object value, CastContext context) {
			if (value instanceof Date) {
				return ((Date)value).getTime();
			}
			else if (value instanceof Calendar) {
				return ((Calendar)value).getTimeInMillis();
			}
			return Numbers.createNumber(value.toString());
		}
	}

	public static class BigDecimalCastor extends AbstractCastor<Object, BigDecimal> {
		public BigDecimalCastor() {
			super(Object.class, BigDecimal.class);
		}

		@Override
		protected BigDecimal convertValue(Object value, CastContext context) {
			if (value instanceof Number) {
				Number num = (Number)value;
				return BigDecimal.valueOf(num.longValue());
			}
			
			return Numbers.toBigDecimal(value.toString());
		}
	}

	public static class BigIntegerCastor extends AbstractCastor<Object, BigInteger> {
		public BigIntegerCastor() {
			super(Object.class, BigInteger.class);
		}
		
		@Override
		protected BigInteger convertValue(Object value, CastContext context) {
			if (value instanceof Number) {
				Number num = (Number)value;
				return BigInteger.valueOf(num.longValue());
			}
			
			return Numbers.toBigInteger(value.toString());
		}
	}
}

