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

import fr.cenra.rhomeo.protocol.p02.ValueType;
import fr.cenra.rhomeo.api.process.Indicator;
import fr.cenra.rhomeo.api.process.Process;
import fr.cenra.rhomeo.api.result.Index;
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.FloreStatement;
import java.beans.IntrospectionException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Function;

/**
 *
 * @author Alexis Manin (Geomatys)
 */
public class AdditionalProcess extends Process {

    private static final Function<Integer, Set<Integer>> SET_VALUE_COMPUTER = key -> new HashSet<>();

    final Session session;
    final Indicator indic;
    final TaxonOperator<FloreStatement> operator;
    final ValueType type;

    public AdditionalProcess(final Session session, final Indicator indic, final TaxonOperator operator, final ValueType valueType) {
        super(operator.getProcessContext());
        this.session = session;
        this.indic = indic;
        this.operator = operator;
        this.type = valueType;
    }

    @Override
    public Indicator getIndicator() {
        return indic;
    }

    @Override
    protected Set<? extends Index> call() throws Exception {
        updateTitle("Calcul du nombre d'observations par valeur indicatrice");
        final int total = 3;
        int progress = 0;

        updateMessage("Tri des données");
        updateProgress(progress++, total);
        final List<FloreStatement> data = operator.getProcessData();
        if (data == null || data.isEmpty())
            return Collections.EMPTY_SET;

        updateMessage("Parcours des données");
        updateProgress(progress++, total);
        int year = data.get(0).getDate().getYear();
        List<NbComputer> computers = new ArrayList<>();
        NbComputer computer = new NbComputer(operator, year, type);
        computers.add(computer);
        for (final FloreStatement st : data) {
            if (st.getDate().getYear() != year) {
                year = st.getDate().getYear();
                computer = new NbComputer(operator, year, type);
                computers.add(computer);
            }

            computer.accept(st);
        }

        updateMessage("Compilation des résultats");
        updateProgress(progress++, total);
        for (final NbComputer nbc : computers) {
            session.getAdditionalValues().add(nbc.getValue());
        }

        return Collections.EMPTY_SET;
    }

    /**
     * Count distinct species found for each indicator value (See {@link FloreBassinReference#getHumidite() }, {@link FloreBassinReference#getNutriment() () }, {@link FloreBassinReference#getCc() ()
     * }).
     */
    private static class NbComputer {

        final int year;
        final ValueType type;
        final Map<Integer, Set<Integer>> values = new HashMap<>();
        final TaxonOperator operator;

        public NbComputer(final TaxonOperator operator, final int year, final ValueType toCompute) {
            this.operator = operator;
            this.year = year;
            type = toCompute;
        }

        /**
         * Update current state by integrating given statement in counting.
         *
         * @param st
         * @throws ReflectiveOperationException
         * @throws IntrospectionException
         */
        void accept(final FloreStatement st) throws ReflectiveOperationException, IntrospectionException {
            final FloreBassinReference ref = operator.getFloreReference(st.getCd_nom());
            if (ref == null)
                return;
            Integer refValue;
            refValue = type.extractor.apply(ref);
            if (refValue != null)
                values.computeIfAbsent(refValue, SET_VALUE_COMPUTER).add(ref.getCd_ref());
        }

        Value getValue() {
            final Value v = new Value(year, type.name());
            for (final Map.Entry<Integer, Set<Integer>> entry : values.entrySet()) {
                v.allValues()[entry.getKey()] = entry.getValue().size();
            }

            return v;
        }
    }
}
