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

import java.math.BigDecimal;
import java.math.BigInteger;
import java.text.NumberFormat;
import java.text.ParsePosition;

/**
 * 文字列を解析して{@link BigInteger}に変換する変換器。 {@link #parse(String, ParsePosition)}では値が
 * BigInteger 型の範囲外ならパースエラーとして扱う。
 * 
 * @author nakamura
 * 
 */
public class ToBigIntegerFormat extends DelegateNumberFormat {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	/**
	 * コンストラクタ。
	 * 
	 * @param format
	 *            数値変換の委譲先。
	 * @throws NullPointerException
	 *             引数が null の場合。
	 */
	public ToBigIntegerFormat(final NumberFormat format) {
		super(format);
	}

	/**
	 * コンストラクタ。 {@link java.text.DecimalFormat}を数値変換の委譲先とする。
	 */
	public ToBigIntegerFormat() {
		super(TextConstants.getToBigDecimalFormat());
	}

	@Override
	public Number parse(
			final String source,
			final ParsePosition parsePosition) {
		final ParsePosition pp = new ParsePosition(0);
		pp.setIndex(parsePosition.getIndex());
		pp.setErrorIndex(parsePosition.getErrorIndex());
		final Number n = super.parse(source, pp);
		if (n != null) {
			if (n instanceof BigInteger) {
				parsePosition.setIndex(pp.getIndex());
				return n;
			} else if (n instanceof BigDecimal) {
				try {
					final BigInteger b = ((BigDecimal) n).toBigIntegerExact();
					parsePosition.setIndex(pp.getIndex());
					return b;
				} catch (final ArithmeticException e) {
					// do nothing.
					return null;
				}
			} else if (n instanceof Long) {
				final long v = n.longValue();
				parsePosition.setIndex(pp.getIndex());
				return new BigDecimal(v).toBigInteger();
			}
			parsePosition.setErrorIndex(parsePosition.getIndex());
		} else {
			parsePosition.setErrorIndex(pp.getIndex());
		}
		return null;
	}
}
