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

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import woolpack.id.IdContext;

/**
 * 値を検証し変換するためのコンテキストです。
 * <br/>適用しているデザインパターン：Interpreter(Context 役)。
 * 
 * @author nakamura
 * 
 */
public class ValidatorContext implements IdContext {
	private String id;
	private Map<String, List<Object>> inputMap;
	private MessageCollectable collectable;
	private String key;
	private int index;

	/**
	 * メッセージを追加します。
	 * 
	 * @param message
	 */
	public void add(final String message) {
		collectable.add(message, this);
	}

	/**
	 * {@link #getKey()}と{@link #getIndex()}で{@link #getInputMap()}を検索し、
	 * その位置の値を返します。
	 * @return 値。
	 */
	public Object getValue() {
		final List<Object> list = inputMap.get(key);
		if (list == null || list.size() <= index) {
			return null;
		} else {
			return list.get(index);
		}
	}

	/**
	 * {@link #getKey()}と{@link #getIndex()}で{@link #getInputMap()}を検索し、
	 * その位置に値を設定します。
	 * @param value
	 */
	public void setValue(final Object value) {
		List<Object> list = inputMap.get(key);
		if (list == null) {
			list = new ArrayList<Object>();
			inputMap.put(key, list);
		}
		if (list.size() == 0 && index == 0) {
			list.add(value);
		} else {
			list.set(index, value);
		}
	}

	public MessageCollectable getCollectable() {
		return collectable;
	}
	public void setCollectable(final MessageCollectable collectable) {
		this.collectable = collectable;
	}
	public String getId() {
		return id;
	}
	public void setId(final String id) {
		this.id = id;
	}
	public Map<String, List<Object>> getInputMap() {
		return inputMap;
	}
	public void setInputMap(final Map<String, List<Object>> inputMap) {
		this.inputMap = inputMap;
	}
	public String getKey() {
		return key;
	}
	public void setKey(final String key) {
		this.key = key;
	}
	public int getIndex() {
		return index;
	}
	public void setIndex(final int index) {
		this.index = index;
	}
}
