/**
 * Copyright (c) 2000-2017 Liferay, Inc. All rights reserved.
 *
 * The contents of this file are subject to the terms of the Liferay Enterprise
 * pSubscription License ("License"). You may not use this file except in
 * compliance with the License. You can obtain a copy of the License by
 * contacting Liferay, Inc. See the License for the specific language governing
 * permissions and limitations under the License, including but not limited to
 * distribution rights of the Software.
 *
 *
 *
 */

package com.liferay.taglib;

import com.liferay.portal.kernel.servlet.taglib.aui.ValidatorTag;
import com.liferay.portal.kernel.util.ListUtil;
import com.liferay.taglib.aui.ValidatorTagImpl;
import com.liferay.taglib.util.IncludeTag;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.jsp.JspException;

/**
 * @author Julio Camarero
 * @author Jorge Ferrer
 * @author Brian Wing Shun Chan
 */
public abstract class BaseValidatorTagSupport extends IncludeTag {

	public void addRequiredValidatorTag() {
		ValidatorTag validatorTag = new ValidatorTagImpl(
			"required", null, null, false);

		addValidatorTag("required", validatorTag);
	}

	public void addValidatorTag(
		String validatorName, ValidatorTag validatorTag) {

		if (_validatorTags == null) {
			_validatorTags = new HashMap<String, ValidatorTag>();
		}

		_validatorTags.put(validatorName, validatorTag);
	}

	@Override
	public int doEndTag() throws JspException {
		updateFormValidatorTags();

		return super.doEndTag();
	}

	public abstract String getInputName();

	@Override
	protected void cleanUp() {
		super.cleanUp();

		_validatorTags = null;
	}

	protected Map<String, ValidatorTag> getValidatorTags() {
		return _validatorTags;
	}

	protected void updateFormValidatorTags() {
		if (_validatorTags == null) {
			return;
		}

		HttpServletRequest request =
			(HttpServletRequest)pageContext.getRequest();

		Map<String, List<ValidatorTag>> validatorTagsMap =
			(Map<String, List<ValidatorTag>>)request.getAttribute(
				"aui:form:validatorTagsMap");

		if (validatorTagsMap != null) {
			List<ValidatorTag> validatorTags = ListUtil.fromMapValues(
				_validatorTags);

			validatorTagsMap.put(getInputName(), validatorTags);
		}
	}

	private Map<String, ValidatorTag> _validatorTags;

}