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

import java.text.Format;
import java.text.ParseException;
import java.text.ParsePosition;

import woolpack.fn.Fn;

/**
 * {@link Format#parseObject(String)}で変換する{@link Fn}です。
 * 「NumberFormat の構文解析問題の解決」
 * (http://www-06.ibm.com/jp/developerworks/java/library/j-numberformat/index.shtml)
 * のテクニックを使用してデータの欠損を検出しています。
 * 
 * @author nakamura
 *
 */
public class ParseConverter implements Fn<String, Object, Exception> {
	private Fn<?, ? extends Format, ? extends Exception> formatFactory;
	
	public ParseConverter(final Fn<?, ? extends Format, ? extends Exception> formatFactory) {
		this.formatFactory = formatFactory;
	}

	/**
	 * @throws ParseException パースに失敗した場合。
	 * @throws Exception 委譲先で例外が発生した場合。
	 */
	public Object exec(final String c) throws Exception {
		final ParsePosition pp = new ParsePosition(0);
		final Format format = formatFactory.exec(null);
		final Object o = format.parseObject(c, pp);
		if (o != null && pp.getIndex() == c.length()) {
			return o;
		} else {
			throw new ParseException("cannot parse " + c + " at " + format, 0);
		}
	}

	public Fn<?, ? extends Format, ? extends Exception> getFormatFactory() {
		return formatFactory;
	}
	public void setFormatFactory(final Fn<?, ? extends Format, ? extends Exception> formatFactory) {
		this.formatFactory = formatFactory;
	}
}
