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

import fr.cenra.rhomeo.api.data.Protocol;
import fr.cenra.rhomeo.api.data.TrackingPoint;
import fr.cenra.rhomeo.api.process.Indicator;
import fr.cenra.rhomeo.api.process.Process;
import fr.cenra.rhomeo.api.process.ProcessContext;
import fr.cenra.rhomeo.api.result.Index;
import fr.cenra.rhomeo.api.process.AbstractIndicator;
import fr.cenra.rhomeo.core.util.TrackingPointComparator;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.OptionalDouble;
import java.util.Set;
import javafx.collections.transformation.SortedList;
import org.apache.sis.util.ArgumentChecks;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;

/**
 *
 * @author Samuel Andrés (Geomatys)
 */
@Component(I01.NAME)
public class I01 extends AbstractIndicator {

    public static final String NAME = "I01";
    public static final String REMARKS = "Niveau d'humidité du sol - Pédologie";

    /**
     * Comparator used to compare {@link PedologyStatement} depths.
     */
    private static final Comparator<PedologyStatement> ASCENDING_DEPTH = (o1, o2) -> o1.getDepth() - o2.getDepth();

    @Autowired
    @Qualifier(P01.NAME)
    private Protocol protocol;

    @Autowired
    private AnnualAverageSoilHumidity annualSpi;

    @Autowired
    private AnnualPointAverageSoilHumidity pointSpi;

    public I01() {
        super(NAME, REMARKS);
    }

    @Override
    public Protocol getProtocol() {
        return protocol;
    }

    @Override
    public Set<Process> createProcesses(final ProcessContext c) {
        ArgumentChecks.ensureNonNull("processContext", c);
        return Collections.singleton(new I01Process(c));
    }

    /**
     * Determine if the given statement can be used for computation for {@link I01}.
     *
     * Relational selection of the temporary table t1 used in expertise.pedo_hygromorphie_par_site view.
     *
     * WITH t1 AS ( SELECT ### FROM expertise.pedo_obs_type_horizon t
     * WHERE t.profondeur_min IS NOT NULL
     * AND t.b1_couleur IS NOT NULL
     * AND t.b2_value IS NOT NULL
     * AND t.b3_chroma IS NOT NULL
     * AND t.c_texture IS NOT NULL
     * AND t.d_structure IS NOT NULL
     * AND t.e_elements_grossiers IS NOT NULL
     * AND t.f_racines IS NOT NULL
     * AND t.g_taches IS NOT NULL)
     *
     * (Source : rhomeo_base_install.sql)
     *
     * This function determines if the {@link PedologyStatement} is computable.
     *
     * The purpose of t1 table used in expertise.pedo_hygromorphie_par_site view
     * is to select expertise.pedo_obs_type_horizon computable tuples.
     *
     * @param ps The statement to check.
     * @return
     */
    public static boolean checkIfComputable(final PedologyStatement ps) {
        return ps.getDepth() > 0 &&
                ps.getColor() != null &&
                ps.getValue() != null &&
                ps.getChroma() != null &&
                ps.getTexture() > 0 &&
                ps.getStructure() > 0 &&
                ps.getRawElements() > 0 &&
                ps.getRoots() > 0 &&
                ps.getStains() > 0;
    }

    @Override
    public String getDefaultIndex() {
        return AnnualAverageSoilHumidity.NAME;
    }

    /**
     * CASE
     *  WHEN t2.profondeur_min :: INTEGER < 25 THEN t2.hz * 2
     *  ELSE t2.hz
     * END AS hz_max,
     *
     * (Source : rhomeo_base_install.sql)
     *
     * @param hz of the statement.
     * @param depth of the statement corresponding to given Hz.
     */
    private static int weightByDepth(final int hz, final int depth) {
        if (depth < 25)
            return hz * 2;
        return hz;
    }

    /**
     * Compute average humidity by tracking point and for each year available.
     */
    private class I01Process extends Process {

        public I01Process(final ProcessContext c) {
            super(c);
        }

        @Override
        protected Set<? extends Index> call() throws Exception {
            updateTitle("Calcul d'humidité");
            updateMessage("Analyse des données");

            final Set<Index> indices = new HashSet<>();

            /**
             * First, we sort data by year and tracking point. For each point,
             * we'll compute an index.
             */
            final ArrayList<TrackingPoint> tPoints = new ArrayList<>(ctx.getTrackingPoints());
            final Map<TrackingPoint, Collection<Integer>> datasetHzMaxByTrackingPoint = new HashMap<>();
            tPoints.sort(new TrackingPointComparator());
            TrackingPoint lastTrackingPoint = null;
            int lastDepth;
            int currentDepth;
            Collection<Integer> tpHZs = new ArrayList<>();

            final long totalProgress = tPoints.size() * 2 + 1;
            long progress = 0;
            for (final TrackingPoint tp : tPoints) {
                updateMessage(new StringBuilder("Hydromorphie des relevés pour ").append(tp.getName()).append(" (").append(tp.getYear()).append(')').toString());
                updateProgress(progress++, totalProgress);
                lastDepth = 0;
                currentDepth = 0;
                if (!tp.equals(lastTrackingPoint)) {
                    if (lastTrackingPoint != null && tpHZs.isEmpty()) {
                        //datasetHzMaxByTrackingPoint.remove(lastTrackingPoint, tpHZs);
                    }
                    lastTrackingPoint = tp;
                    tpHZs = new ArrayList<>();
                    datasetHzMaxByTrackingPoint.put(tp, tpHZs);
                }

                final SortedList<PedologyStatement> statements = ctx.getData().getSubSet(tp).sorted(ASCENDING_DEPTH);
                for (final PedologyStatement statement : statements) {
                    if (statement.getDepth() > currentDepth) {
                        lastDepth = currentDepth;
                    }
                    if (checkIfComputable(statement)) {
                        tpHZs.add(weightByDepth(getHzCandidate(statement, lastDepth), lastDepth));
                    }

                    currentDepth = statement.getDepth();
                }
            }

            // Compute indice for each years, based on results found for points.
            // We compute the average of all retained values for each point of a year,
            final HashMap<Integer, int[]> sumsByYear = new HashMap<>();
            int[] sum;
            for (final TrackingPoint pt : datasetHzMaxByTrackingPoint.keySet()) {
                updateMessage(new StringBuilder("Hydromorphie moyenne pour ").append(pt.getName()).append(" (").append(pt.getYear()).append(')').toString());
                updateProgress(progress++, totalProgress);
                final OptionalDouble optValue = datasetHzMaxByTrackingPoint.get(pt).stream().mapToInt(i -> i).average();
                if (optValue.isPresent()) {
                    indices.add(pointSpi.createIndex(optValue.getAsDouble(), pt));
                }

                sum = sumsByYear.computeIfAbsent(pt.getYear(), i -> new int[]{0, 0});
                for (final Integer i : datasetHzMaxByTrackingPoint.get(pt)) {
                    sum[0] += i;
                    sum[1]++;
                }
            }

            updateMessage("Calcul des hydromorphies par année");
            updateProgress(progress++, totalProgress);
            for (final Map.Entry<Integer, int[]> year : sumsByYear.entrySet()) {
                indices.add(annualSpi.createIndex(year.getValue()[0] / (double) year.getValue()[1], year.getKey()));
            }

            return indices;
        }

        @Override
        public Indicator getIndicator() {
            return I01.this;
        }
    }

    // Color
    private static final String GLEY1 = "GLEY1";
    private static final String GLEY2 = "GLEY2";

    // Von-Post
    private static final String H1 = "H1";
    private static final String H2 = "H2";
    private static final String H3 = "H3";
    private static final String H4 = "H4";
    private static final String H5 = "H5";
    private static final String H6 = "H6";
    private static final String H7 = "H7";
    private static final String H8 = "H8";
    private static final String H9 = "H9";
    private static final String H10 = "H10";

    /**
     * CASE
     *  WHEN obs_pedo.f_racines > 1 AND obs_pedo.c_texture = 1 AND obs_pedo.numero = 1 AND obs_pedo.q_von_post IS NULL THEN '1'::text
     *  ELSE '0'::text
     * END AS "L"
     *
     * (Source : rhomeo_base_install.sql)
     */
    static int getL(final PedologyStatement ps, int minDepth) {
        return ps.getRoots() > 1 && ps.getTexture()==1 && minDepth <= 0 && ps.getVonPost()==null ? 1 : 0;
    };

    /**
     * CASE
     *  WHEN obs_pedo.c_texture > 1 AND (obs_pedo.g_taches = 3 OR obs_pedo.b1_couleur = 'GLEY1'::text AND obs_pedo.b2_value <> '7'::text AND obs_pedo.b2_value <> '8'::text OR obs_pedo.b1_couleur = 'GLEY2'::text AND obs_pedo.b2_value <> '7'::text AND obs_pedo.b2_value <> '8'::text) THEN '2'::text
     *  ELSE '0'::text
     * END AS "Gr"
     *
     * (Source : rhomeo_base_install.sql)
     */
    static int getGr(final PedologyStatement ps) {
        return ps.getTexture() > 1
                && (ps.getStains()==3
                    || GLEY1.equals(ps.getColor())
                    && !"7".equals(ps.getValue())
                    && !"8".equals(ps.getValue())
                    || GLEY2.equals(ps.getColor())
                    && !"7".equals(ps.getValue())
                    && !"8".equals(ps.getValue())) ? 2 : 0;
    };

    /**
     * CASE
     *  WHEN obs_pedo.c_texture > 1 AND obs_pedo.g_taches = 2 AND obs_pedo.h_abondance > 0 THEN '1'::text
     *  ELSE '0'::text
     * END AS "Go"
     *
     * (Source : rhomeo_base_install.sql)
     */
    static int getGo(final PedologyStatement ps) {
        return ps.getTexture() > 1 && ps.getStains()==2 && ps.getAbundance()>0 ? 1 : 0;
    };

    /**
     * CASE
     *  WHEN obs_pedo.c_texture > 1 AND obs_pedo.c_texture < 4 AND obs_pedo.o_friabilite > 2 AND obs_pedo.d_structure = 1 THEN '1'::text
     *  ELSE '0'::text
     * END AS "J"
     *
     * (Source : rhomeo_base_install.sql)
     */
    static int getJ(final PedologyStatement ps) {
        return ps.getTexture()>1 && ps.getTexture()<4 && ps.getFriability()>2 && ps.getStructure()==1 ? 1 : 0;
    };

    /**
     * CASE
     *  WHEN obs_pedo.b2_value::numeric > 4.5 AND obs_pedo.q_von_post IS NULL AND obs_pedo.o_friabilite < 2 AND obs_pedo.m_plasticite = 1 THEN '3'::text
     *  ELSE '0'::text
     * END AS "T"
     *
     * (Source : rhomeo_base_install.sql)
     *
     * @throws IllegalArgumentException if the statement "value" field is null.
     * @throws NumberFormatException if the string does not contain a parsable number.
     */
    static int getT(final PedologyStatement ps) {
        // Missing fields
        if (ps.getValue() == null || ps.getFriability() < 1)
            return 0;
        return (Float.valueOf(ps.getValue())>4.5 && ps.getVonPost()==null && ps.getFriability()<2 && ps.getPlasticity()==1) ? 3 : 0;
    };

    /**
     * CASE
     *  WHEN obs_pedo.c_texture = 1 AND obs_pedo.d_structure > 10 AND (obs_pedo.q_von_post = 'H1'::text OR obs_pedo.q_von_post = 'H2'::text OR obs_pedo.q_von_post = 'H3'::text) THEN '3'::text
     *  ELSE '0'::text
     * END AS "Hf"
     *
     * (Source : rhomeo_base_install.sql)
     */
    static int getHf(final PedologyStatement ps) {
        return ps.getTexture()==1
                && ps.getStructure()>10
                && (H1.equals(ps.getVonPost())
                || H2.equals(ps.getVonPost())
                || H3.equals(ps.getVonPost())) ? 3 : 0;
    };

    /**
     * CASE
     *  WHEN obs_pedo.c_texture = 1 AND (obs_pedo.q_von_post = 'H3'::text OR obs_pedo.q_von_post = 'H4'::text OR obs_pedo.q_von_post = 'H5'::text OR obs_pedo.q_von_post = 'H6'::text OR obs_pedo.q_von_post = 'H7'::text) THEN '2'::text
     *  ELSE '0'::text
     * END AS "Hm"
     *
     * (Source : rhomeo_base_install.sql)
     */
    static int getHm(final PedologyStatement ps) {
        return ps.getTexture()==1 && (H3.equals(ps.getVonPost())
                || H4.equals(ps.getVonPost()) || H5.equals(ps.getVonPost())
                || H6.equals(ps.getVonPost()) || H7.equals(ps.getVonPost())) ? 2 : 0;
    };

    /**
     * CASE
     *  WHEN obs_pedo.c_texture = 1 AND (obs_pedo.q_von_post = 'H8'::text OR obs_pedo.q_von_post = 'H9'::text OR obs_pedo.q_von_post = 'H10'::text)
     * OR obs_pedo.c_texture >= 3 AND (obs_pedo.q_von_post = 'H3'::text OR obs_pedo.q_von_post = 'H4'::text OR obs_pedo.q_von_post = 'H5'::text OR obs_pedo.q_von_post = 'H6'::text OR obs_pedo.q_von_post = 'H7'::text OR obs_pedo.q_von_post = 'H8'::text OR obs_pedo.q_von_post = 'H9'::text OR obs_pedo.q_von_post = 'H10'::text) THEN '2'::text
     *  ELSE '0'::text
     * END AS "Hs"
     *
     * (Source : rhomeo_base_install.sql)
     */
    static int getHs(final PedologyStatement ps) {
        return ps.getTexture()==1 && (H8.equals(ps.getVonPost()) || H9.equals(ps.getVonPost())
                    || H10.equals(ps.getVonPost()))
                || ps.getTexture()>=3 && (H3.equals(ps.getVonPost()) || H4.equals(ps.getVonPost())
                    || H5.equals(ps.getVonPost()) || H6.equals(ps.getVonPost())
                    || H7.equals(ps.getVonPost()) || H8.equals(ps.getVonPost())
                    || H9.equals(ps.getVonPost()) || H10.equals(ps.getVonPost())) ? 2 : 0;
    };

    /**
     * CASE
     *  WHEN obs_pedo.g_taches = 1 AND obs_pedo.q_von_post IS NULL AND (obs_pedo.c_texture = 1 AND obs_pedo.d_structure < 10 AND obs_pedo.d_structure > 3 OR obs_pedo.c_texture > 1 AND obs_pedo.d_structure > 10) THEN '2'::text
     *  ELSE '0'::text
     * END AS "Org"
     *
     * (Source : rhomeo_base_install.sql)
     */
    static int getOrg(final PedologyStatement ps) {
        return ps.getStains()==1 && ps.getVonPost()==null
                && (ps.getTexture()==1 && ps.getStructure()<10 && ps.getStructure()>3
                    || ps.getTexture()>1 && ps.getStructure()>10) ? 2 : 0;
    };

    /**
     * CASE
     *  WHEN obs_pedo.c_texture = 1 AND obs_pedo.q_von_post IS NULL AND obs_pedo.k_humidite <= 3 AND (obs_pedo.d_structure <= 3 OR obs_pedo.d_structure = 11) THEN '1'::text
     *  ELSE '0'::text
     * END AS "Ha_LH"
     *
     * (Source : rhomeo_base_install.sql)
     */
    static int getHa_LH(final PedologyStatement ps) {
        // Missing fields
        if (ps.getHumidity() < 1 || ps.getStructure() < 1)
            return 0;
        return ps.getTexture()==1
                && ps.getVonPost()==null
                && ps.getHumidity()<=3
                && (ps.getStructure()<=3 || ps.getStructure()==11) ? 1 : 0;
    };

    /**
     * Greatest(t1."l", t1."gr", t1."go", t1."j", t1."t", t1."hf", t1."hm", t1."hs", t1."org", t1."ha_lh"))
     *
     * (Source : rhomeo_base_install.sql)
     */
    static Integer getHzCandidate(final PedologyStatement ps, int lastDepth) {
        final int[] candidates = new int[]{
            getL(ps, lastDepth),
            getGr(ps),
            getGo(ps),
            getJ(ps),
            getT(ps),
            getHf(ps),
            getHm(ps),
            getHs(ps),
            getOrg(ps),
            getHa_LH(ps)
        };

        Arrays.sort(candidates);
        return candidates[candidates.length -1];
    }
}
