/*
 * Copyright (C) 2018-2022 Toshiaki Maki <makingx@gmail.com>
 *
 * 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 org.xbib.datastructures.validation.factory;

import java.util.function.Function;

import org.xbib.datastructures.validation.builder.ValidatorBuilder;
import org.xbib.datastructures.validation.core.BiValidator;
import org.xbib.datastructures.validation.core.BiValidator.ErrorHandler;
import org.xbib.datastructures.validation.jsr305.Nullable;
import org.xbib.datastructures.validation.message.MessageFormatter;

/**
 * A factory class of <code>BiValidator</code>. It can be used to manage the common
 * configurations of <code>BiValidator</code> in IoC container etc.<br>
 *
 * In case of Spring Framework, you can define <code>BiValidatorFactory</code> as follows:
 *
 * <pre>
 *{@literal @Bean}
 * public BiValidatorFactory&lt;Errors&gt; biValidatorFactory(MessageSource messageSource) {
 *   MessageFormatter messageFormatter = new MessageSourceMessageFormatter(messageSource::getMessage);
 *   return new BiValidatorFactory&lt;&gt;(null, messageFormatter, Errors::rejectValues);
 * }
 * </pre>
 *
 * A component can create a validator like following:
 * 
 * <pre>
 *{@literal @RestController}
 * public class OrderController {
 *     private final BiValidator&lt;CartItem, Errors&gt; validator;
 *
 *     public OrderController(BiValidatorFactory&lt;Errors&gt; factory) {
 *         this.validator = factory.validator(builder -> builder.constraint(...));
 *     }
 * }
 * </pre>
 *
 * @param <E> the type of the errors object
 */
public class BiValidatorFactory<E> extends ValidatorFactorySupport {
	private final ErrorHandler<E> errorHandler;

	public BiValidatorFactory(@Nullable String messageKeySeparator,
			@Nullable MessageFormatter messageFormatter,
			@Nullable ErrorHandler<E> errorHandler) {
		super(messageKeySeparator, messageFormatter);
		this.errorHandler = errorHandler;
	}

	public BiValidatorFactory(@Nullable ErrorHandler<E> errorHandler) {
		this(null, null, errorHandler);
	}

	public <T> BiValidator<T, E> validator(Function<ValidatorBuilder<T>, ValidatorBuilder<T>> constraints) {
		if (this.errorHandler == null) {
			throw new IllegalArgumentException("'errorHandler' must not be null.");
		}
		final ValidatorBuilder<T> builder = super.initBuilder();
		return constraints.apply(builder).build(this.errorHandler);
	}
}
