/*
 * 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.FieldPosition;
import java.text.Format;
import java.text.ParsePosition;
import java.util.regex.Pattern;

import woolpack.utils.CheckUtils;

/**
 * 正規表現を使用して文字列をフォーマットする変換器。
 * {@link #format(Object, StringBuffer, FieldPosition)}
 * ・{@link #parseObject(String, ParsePosition)}
 * とも同一の変換を行うため、可逆ではない。
 * 
 * @author nakamura
 * 
 */
public class RegExpFormat extends Format {

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

	private final Pattern pattern;

	private final String replacement;

	/**
	 * コンストラクタ。
	 * 
	 * @param pattern
	 *            正規表現。
	 * @param replacement
	 *            変換パターン。
	 * @throws NullPointerException
	 *             引数のいずれかが null の場合。
	 * @throws StringIndexOutOfBoundsException
	 *             replacement が空の場合。
	 */
	public RegExpFormat(final Pattern pattern, final String replacement) {
		super();
		CheckUtils.checkNotNull(pattern);
		CheckUtils.checkNotEmpty(replacement);

		this.pattern = pattern;
		this.replacement = replacement;
	}

	/**
	 * コンストラクタ。
	 * 
	 * @param pattern
	 *            正規表現。
	 * @param replacement
	 *            変換パターン。
	 * @throws NullPointerException
	 *             引数のいずれかが null の場合。
	 * @throws StringIndexOutOfBoundsException
	 *             replacement が空の場合。
	 * @throws PatternSyntaxException
	 *             表現の構文が無効である場合。
	 */
	public RegExpFormat(final String pattern, final String replacement) {
		this(Pattern.compile(pattern), replacement);
	}

	@Override
	public StringBuffer format(final Object obj, final StringBuffer toAppendTo,
			final FieldPosition pos) {
		final int start = toAppendTo.length();
		toAppendTo.append(convert((String) obj));
		pos.setBeginIndex(start);
		pos.setEndIndex(toAppendTo.length());
		return toAppendTo;
	}

	@Override
	public Object parseObject(final String source, final ParsePosition pos) {
		final int i = pos.getIndex();
		pos.setIndex(source.length());
		return convert(source.substring(i));
	}

	private String convert(final String before) {
		return pattern.matcher(before).replaceAll(replacement);
	}

	public Pattern getPattern() {
		return pattern;
	}

	public String getReplacement() {
		return replacement;
	}
}
