/**
 * Copyright © CENRA (2016)
 *
 * remi.clement@espaces-naturels.fr
 * 
 * This software is a multi-platform and portable application based on 
 * the scientifical toolbox to monitor wetlands. With this toolbox it’s 
 * possible to calculate indicators «RhoMéO» to monitor quality, 
 * fonctionalities and urban and agricultural pressures of wetlands. 
 * Indicators are calculated using naturalist data entered and/or imported,
 * and geographic data downloaded from a geographic server.
 * 
 * This software is governed by the CeCILL license under French law and
 * abiding by the rules of distribution of free software.  You can  use, 
 * modify and/ or redistribute the software under the terms of the CeCILL
 * license as circulated by CEA, CNRS and INRIA at the following URL
 * "http://www.cecill.info". 
 * 
 * As a counterpart to the access to the source code and  rights to copy,
 * modify and redistribute granted by the license, users are provided only
 * with a limited warranty  and the software's author,  the holder of the
 * economic rights,  and the successive licensors  have only  limited
 * liability. 
 * 
 * In this respect, the user's attention is drawn to the risks associated
 * with loading,  using,  modifying and/or developing or reproducing the
 * software by the user in light of its specific status of free software,
 * that may mean  that it is complicated to manipulate,  and  that  also
 * therefore means  that it is reserved for developers  and  experienced
 * professionals having in-depth computer knowledge. Users are therefore
 * encouraged to load and test the software's suitability as regards their
 * requirements in conditions enabling the security of their systems and/or 
 * data to be ensured and,  more generally, to use and operate it in the 
 * same conditions as regards security. 
 * 
 * The fact that you are presently reading this means that you have had
 * knowledge of the CeCILL license and that you accept its terms.
*/
package fr.cenra.rhomeo.protocol.p02.validation;

import fr.cenra.rhomeo.api.data.Statement;
import fr.cenra.rhomeo.api.process.ProcessContext;
import fr.cenra.rhomeo.core.RhomeoRuntimeException;
import fr.cenra.rhomeo.core.Session;
import fr.cenra.rhomeo.core.data.reference.FloreBassinReference;
import fr.cenra.rhomeo.protocol.TaxonOperator;
import fr.cenra.rhomeo.protocol.p02.validation.DeterminedFloreSpecies.Validator;
import java.beans.IntrospectionException;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import javax.validation.Constraint;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import javax.validation.Payload;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

/**
 * A constraint annotation to check if a given {@link FloreBassinReference#getCd_nom() }
 * is known as species or gender.
 *
 * @author Alexis Manin (Geomatys)
 */
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
@Constraint(validatedBy = Validator.class)
@Documented
public @interface DeterminedFloreSpecies {

    static final String INVALID_SUFFIX = "sp.";

    String message() default "L'espèce n'est pas déterminante";

    Class<?>[] groups() default {};

    Class<? extends Payload>[] payload() default {};

    @Component
    @Scope("prototype")
    static class Validator implements ConstraintValidator<DeterminedFloreSpecies, Integer> {

        @Autowired
        Session session;

        TaxonOperator<Statement> operator;

        @Override
        public void initialize(DeterminedFloreSpecies constraintAnnotation) {
            operator = TaxonOperator.getOrCreate(new ProcessContext(session.getDataset(), session.getDataContext()));
        }

        @Override
        public boolean isValid(Integer value, ConstraintValidatorContext context) {
            final FloreBassinReference ref;
            try {
                if (value == null || (ref = operator.getFloreReference(value)) == null)
                    return true; // Not our job to check null values / unkown species.
            } catch (ReflectiveOperationException | IntrospectionException ex) {
                throw new RhomeoRuntimeException(ex);
            }

            if (ref.getNom() != null && ref.getNom().toLowerCase().endsWith(INVALID_SUFFIX)) {
                context.buildConstraintViolationWithTemplate(
                        "Les espèces déterminées au genre ne sont pas prises en compte dans les calculs : ".concat(ref.getNom())
                ).addConstraintViolation().disableDefaultConstraintViolation();
                return false;
            }

            return true;
        }
    }
}
