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

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import woolpack.validator.SimpleMessageCollector;
import woolpack.validator.ValidatorContext;
import woolpack.validator.ValidatorExpression;

/**
 * {@link ValidatorExpression}に委譲する{@link Convertable}。
 * 適用しているパターン：Adapter。
 * @author nakamura
 *
 */
public class ValidatorConverter implements Convertable {
	private final ValidatorExpression expression;
	
	/**
	 * コンストラクタ。
	 * @param expression 変換処理の委譲先。
	 * @throws NullPointerException 引数のいずれかが null の場合。
	 */
	public ValidatorConverter(final ValidatorExpression expression){
		expression.getClass();
		this.expression = expression;
	}

	public Object convert(final Object beforeValue, final Class toType, final String propertyName) {
		final ValidatorContext context = new ValidatorContext();
		final SimpleMessageCollector collector = new SimpleMessageCollector();
		context.setCollectable(collector);
		context.setInputMap(new HashMap<String,List<Object>>(1));
		context.getInputMap().put(propertyName, new ArrayList<Object>(1));
		context.setTmpValue(beforeValue);
		context.setTmpKey(propertyName);
		expression.interpret(context);
		return context.getTmpValue();
	}

	public ValidatorExpression getExpression() {
		return expression;
	}
}
