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

import fr.cenra.rhomeo.api.data.Protocol;
import fr.cenra.rhomeo.api.data.Reference;
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.core.data.reference.OrthopteraIndicatorReference;
import fr.cenra.rhomeo.protocol.TaxonOperator;
import fr.cenra.rhomeo.protocol.p02.FloreStatement;
import fr.cenra.rhomeo.protocol.p05.OrthopteraStatement;
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 java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.function.Function;
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;

/**
 *
 * @author Alexis Manin (Geomatys)
 */
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@Constraint(validatedBy = IndicatorTaxon.Validator.class)
@Documented
public @interface IndicatorTaxon {
    String message() default "Présence de taxons sans valeur indicatrice";

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

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

    /**
     *
     * @return Type of reference to check values against.
     */
    Class<? extends Reference> type();

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

        @Autowired
        private Session session;

        TaxonOperator<Statement> operator;
        Function<Statement, Pair> isIndicator;

        @Override
        public void initialize(IndicatorTaxon constraintAnnotation) {
            if (FloreBassinReference.class.isAssignableFrom(constraintAnnotation.type())) {
                operator = TaxonOperator.getOrCreate(new ProcessContext(session.getDataset(), session.getDataContext()));
                isIndicator = st -> {
                    FloreBassinReference ref;
                    try {
                        ref = operator.getFloreReference(((FloreStatement)st).getCd_nom());
                    } catch (Exception ex) {
                        throw new RhomeoRuntimeException(ex);
                    }
                    return ref == null ? new Pair(0, false) : new Pair(ref.getCd_ref(), !(ref.getCc() == null && ref.getHumidite() == null && ref.getNutriment() == null));
                };

            } else if (OrthopteraIndicatorReference.class.isAssignableFrom(constraintAnnotation.type())) {
                operator = TaxonOperator.getOrCreate(new ProcessContext(session.getDataset(), session.getDataContext()));
                isIndicator = st -> {
                    OrthopteraIndicatorReference ref;
                    try {
                        final Integer cdRef = operator.getCdRef(((OrthopteraStatement)st).getCd_nom());
                        ref = operator.getOrthopteraReference(cdRef);
                    } catch (Exception ex) {
                        throw new RhomeoRuntimeException(ex);
                    }
                    return ref == null ? new Pair(0, false) : new Pair(ref.getCd_ref(), ref.getHs_val() > 0 || ref.getDm_val() > 0);
                };

            } else {
                throw new IllegalArgumentException("Unsupported reference type : ".concat(String.valueOf(constraintAnnotation.type())));
            }
        }

        @Override
        public boolean isValid(Protocol value, ConstraintValidatorContext context) {
            final Set<Integer> distinctRefs = new HashSet<>();
            int indicator = 0;
            Pair p;
            for (final Statement st : ((List<Statement>)session.getDataset().getItems())) {
                p = isIndicator.apply(st);
                distinctRefs.add(p.cd_ref);
                if (p.isIndicator)
                    indicator++;
            }

            final int total = distinctRefs.size();
            if (indicator < total) {
                context.buildConstraintViolationWithTemplate(
                        new StringBuilder().append(total - indicator)
                                .append(" taxons n'ont pas de valeur indicatrice parmi les ")
                                .append(total).append(" espèces saisies")
                                .toString()
                ).addConstraintViolation().disableDefaultConstraintViolation();
                return false;
            }
            return true;
        }
    }

    static class Pair {
        final int cd_ref;
        final boolean isIndicator;

        public Pair(int cd_ref, boolean isIndicator) {
            this.cd_ref = cd_ref;
            this.isIndicator = isIndicator;
        }
    }
}
