/*
 * 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.text.NumberFormat;
import java.text.ParsePosition;

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

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

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

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

	@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) {
			final int v = n.intValue();
			if ((n instanceof Long) && n.longValue() == v) {
				parsePosition.setIndex(pp.getIndex());
				return Integer.valueOf(v);
			}
			parsePosition.setErrorIndex(parsePosition.getIndex());
		} else {
			parsePosition.setErrorIndex(pp.getIndex());
		}
		return null;
	}
}
