/*
 * 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> {
	private Fn<?, Format> formatFactory;
	
	public ParseConverter(final Fn<?, Format> formatFactory) {
		this.formatFactory = formatFactory;
	}

	/**
	 * @throws IllegalArgumentException ({@link ParseException})。
	 */
	public Object exec(final String c) {
		final ParsePosition pp = new ParsePosition(0);
		final Object o = formatFactory.exec(null).parseObject(c, pp);
		if (o != null && pp.getIndex() == c.length()) {
			return o;
		} else {
			throw new IllegalArgumentException(new ParseException("cannot parse", 0));
		}
	}

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