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

import fr.cenra.rhomeo.api.data.Protocol;
import fr.cenra.rhomeo.api.process.ProcessContext;
import fr.cenra.rhomeo.api.result.Index;
import fr.cenra.rhomeo.core.RhomeoCore;
import fr.cenra.rhomeo.core.RhomeoRuntimeException;
import fr.cenra.rhomeo.core.Session;
import fr.cenra.rhomeo.protocol.TaxonOperator;
import fr.cenra.rhomeo.protocol.p06.Behavior;
import fr.cenra.rhomeo.protocol.p06.BehaviorSpi;
import fr.cenra.rhomeo.protocol.p06.OdonataStatement;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

/**
 *
 * @author Alexis Manin (Geomatys)
 */
@Component
@Scope("prototype")
public class BehaviorCoverageValidator implements ConstraintValidator<BehaviorCoverage, Protocol> {

    private static final int[] ACCEPTED_BEHAVIORS = new int[] {Behavior.PON.getCode(), Behavior.IMM.getCode(), Behavior.EXU.getCode()};
    static {
        Arrays.sort(ACCEPTED_BEHAVIORS);
    }

    @Autowired
    Session session;

    @Autowired
    BehaviorSpi bSpi;

    /**
     * Minimum rate of statements which must have an accepted behavior by year.
     */
    private float min = Float.NaN;

    @Override
    public void initialize(BehaviorCoverage constraintAnnotation) {
        min = constraintAnnotation.min();
    }

    @Override
    public boolean isValid(Protocol value, ConstraintValidatorContext context) {
        try {
            final ProcessContext pContext = new ProcessContext(session.getDataset(), session.getDataContext());
            final Set<Index<Float>> behaviors = computeBehaviorIndices(
                    pContext, TaxonOperator.getOrCreate(pContext), bSpi);

            boolean valid = true;
            for (final Index<Float> idx : behaviors) {
                if (idx.getValue() < min) {
                    addConstraintViolation(context, idx.getYear(), idx.getValue());
                    valid = false;
                }
            }

            if (!valid) {
                context.disableDefaultConstraintViolation();
            }
            return valid;
        } catch (Exception e) {
            throw new RhomeoRuntimeException(e);
        }
    }

    private void addConstraintViolation(final ConstraintValidatorContext context, final int year, float value) {
        final StringBuilder builder = new StringBuilder("Niveau d'autochtonie insuffisant pour l'année ").append(year)
                .append(System.lineSeparator())
                .append("Pourcentage calculé : ").append(RhomeoCore.SIMPLE_DECIMAL_FORMAT.format(value)).append('%')
                .append(System.lineSeparator())
                .append("Minimum attendu : ").append(RhomeoCore.SIMPLE_DECIMAL_FORMAT.format(min)).append('%')
                .append(System.lineSeparator())
                .append("Comportements pris en compte pour l'autochtonie : ");
        for (final int i : ACCEPTED_BEHAVIORS) {
            RhomeoCore.getByCode(Behavior.class, i).ifPresent(b -> builder.append(b.getValue()).append(", "));
        }

        final int lastSeparator = builder.lastIndexOf(", ", builder.length() - 2);
        if (lastSeparator > 0) {
            builder.delete(lastSeparator, builder.length());
        }
        context.buildConstraintViolationWithTemplate(builder.toString()).addConstraintViolation();
    }

    private static boolean hasAcceptedBehavior(final OdonataStatement st) {
        return Arrays.binarySearch(ACCEPTED_BEHAVIORS, st.getBehavior()) >= 0;
    }

    public static Set<Index<Float>> computeBehaviorIndices(final ProcessContext ctx, TaxonOperator operator, BehaviorSpi idxSpi) throws Exception {
        // Dataset snapshot, in chronological order.
        final List<OdonataStatement> statements = operator.getProcessData();

        final OdonataStatement st0;
        if (statements.isEmpty() || (st0 = statements.get(0)).getDate() == null) {
            return Collections.EMPTY_SET;
        }

        int year = st0.getDate().getYear(); // Init year to the year of the first statement (the oldest one).

        Integer cdRef;
        final Set<Index<Float>> results = new HashSet<>();
        final Set<Integer> distinctCdRefs = new HashSet<>();// distinct species found this year.
        final Set<Integer> bestCdRefs = new HashSet<>();// Species with an accepted behavior, for a given year.
        for (final OdonataStatement statement : statements) { // Chronological loop.

            if (statement.getDate() == null)
                break;

            final int stYear = statement.getDate().getYear();

            // Case of year change : examine if the constraint is violated or not for the previous year.
            if (stYear > year) {

                // Check constraint violation of the previous year.
                results.add(
                        idxSpi.createIndex((100f * bestCdRefs.size()) / distinctCdRefs.size(), year)
                );
                // Resets for the new year.
                distinctCdRefs.clear();
                bestCdRefs.clear();
                year = stYear;
            }

            // Check statement behavior
            cdRef = operator.getCdRef(statement.getCd_nom());
            if (hasAcceptedBehavior(statement)) {
                bestCdRefs.add(cdRef);
            }
            distinctCdRefs.add(cdRef);
        }

        // Check constraint violation of the last year (including the case if the dataset contains only one year).
        results.add(
                idxSpi.createIndex((100f * bestCdRefs.size()) / distinctCdRefs.size(), year)
        );

        return results;
    }
}
