/*
 * Copyright (c) 2003, Morpho Project.
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * 1. Redistributions of source code must retain the above copyright notice,
 *    this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright notice,
 *    this list of conditions and the following disclaimer in the documentation
 *    and/or other materials provided with the distribution.
 * 3. Neither the name of the Morpho Project nor the names of its contributors
 *    may be used to endorse or promote products derived from this software
 *    without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 */
package jp.morpho.webapp.validator;

import java.lang.reflect.Method;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Locale;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import jp.morpho.webapp.FrameworkContext;
import jp.morpho.webapp.PluginKeys;
import jp.morpho.webapp.resource.MessageResourceManager;
import jp.morpho.webapp.servlet.http.HttpActionRequest;
import jp.morpho.webapp.servlet.http.HttpSessionAttributeNames;

/**
 * @author Kenichi Fukuda
 */
public class ValidatorSequence
	extends ArrayList
	implements FieldValidator
{
	private String name = null;

	public void setFieldName(String name)
	{
		this.name = name;
	}

	public String getFieldName()
	{
		return name;
	}

	public void validate(HttpActionRequest request) throws ValidationException
	{
		boolean errorFlag = false;

		try
		{
			for (int i = 0; i < this.size(); i++)
			{
				FieldValidatorEntry entry = (FieldValidatorEntry)this.get(i);
				FieldValidator validator = entry.getValidator();
				String messageId = entry.getMessageId();
				try
				{
					validator.validate(request);
				}
				catch (Exception e)
				{
					errorFlag = true;
					if (validator.getFieldName() != null)
					{
						String message = null;
						if (messageId != null)
						{
							message = getMessage(request, validator, messageId);
						}
						ValidationState vs = ValidationState.getInstance(request);
						vs.addInvalidField(validator.getFieldName(), message);
					}
				}
			}

			if (errorFlag)
			{
				throw new ValidationException("");
			}
		}
		catch (Exception e)
		{
			throw new ValidationException(e.getMessage());
		}

	}

	private String getMessage(HttpActionRequest request, FieldValidator validator, String messageId)
	{
		try
		{
			FrameworkContext fc = FrameworkContext.getInstance(request.getSession().getServletContext());
			MessageResourceManager mrm = (MessageResourceManager)fc.get(PluginKeys.messageResourceManager);

			Locale locale = (Locale)request.getSession().getAttribute(HttpSessionAttributeNames.locale);
			if (locale == null)
			{
				locale = request.getLocale();
			}
			String message = mrm.getMessage(messageId, null, locale);

			Pattern formatPattern = Pattern.compile("[{][^}]*[}]");
			Matcher formatMatcher = formatPattern.matcher(message);

			StringBuffer messageBuf = new StringBuffer();
			ArrayList messageArgList = new ArrayList();
			for (int j = 0; formatMatcher.find(); j++)
			{
				String format = message.substring(formatMatcher.start(), formatMatcher.end());

				Pattern fieldPattern = Pattern.compile("[^{][^,}]*");
				Matcher fieldMatcher = fieldPattern.matcher(format);

				fieldMatcher.find();

				String fieldName = format.substring(fieldMatcher.start(), fieldMatcher.end()).trim();

				String messageFormat = fieldMatcher.replaceFirst("" + j);
				formatMatcher.appendReplacement(messageBuf, messageFormat);

				String methodName = "get";
				if (fieldName.length() == 1)
				{
					methodName += fieldName.toUpperCase();
				}
				else if (fieldName.length() > 1)
				{
					methodName += fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1);
				}
				Method method = validator.getClass().getMethod(methodName, null);
				Object messageArg = method.invoke(validator, null);
				if (fieldName.equalsIgnoreCase("fieldname") || fieldName.equalsIgnoreCase("compareFieldName"))
				{
					messageArg = mrm.getFieldName((String)messageArg, locale);
				}
				else if (fieldName.equalsIgnoreCase("compareOperator"))
				{
					messageArg = mrm.getMessage("compareOperator." + (String)messageArg, null, locale);
				}
				messageArgList.add(messageArg);
			}
			if (messageArgList.size() > 0)
			{
				formatMatcher.appendTail(messageBuf);
				MessageFormat mf = new MessageFormat(messageBuf.toString());
				message = mf.format(messageArgList.toArray());
			}

			return message;
		}
		catch (Exception e)
		{
			Logger log = Logger.getLogger("jp.morpho");
			log.log(Level.WARNING, e.getMessage(), e);
		}

		return null;
	}

}
