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

import fr.cenra.rhomeo.api.data.Protocol;
import fr.cenra.rhomeo.api.process.Process;
import fr.cenra.rhomeo.api.process.ProcessContext;
import fr.cenra.rhomeo.api.process.AbstractIndicator;
import fr.cenra.rhomeo.api.process.Indicator;
import fr.cenra.rhomeo.api.result.Index;
import fr.cenra.rhomeo.core.RhomeoCore;
import fr.cenra.rhomeo.protocol.p03.index.FirstDecileSpi;
import fr.cenra.rhomeo.protocol.p03.index.FirstQuartileSpi;
import fr.cenra.rhomeo.protocol.p03.index.LastDecileSpi;
import fr.cenra.rhomeo.protocol.p03.index.MaxSpi;
import fr.cenra.rhomeo.protocol.p03.index.MedianeSpi;
import fr.cenra.rhomeo.protocol.p03.index.MinSpi;
import fr.cenra.rhomeo.protocol.p03.index.ThirdQuartileSpi;
import java.time.LocalDate;
import java.time.Month;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
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(I03.NAME)
public class I03 extends AbstractIndicator {

    public static final String NAME = "I03";
    public static final String REMARKS = "Dynamique hydrologique - piézomètre";

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

    @Autowired
    MinSpi minSpi;

    @Autowired
    FirstDecileSpi fdSpi;

    @Autowired
    FirstQuartileSpi fqSpi;

    @Autowired
    MedianeSpi medianeSpi;

    @Autowired
    ThirdQuartileSpi tqSpi;

    @Autowired
    LastDecileSpi tdSpi;

    @Autowired
    MaxSpi maxSpi;

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

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

    @Override
    public Set<Process> createProcesses(ProcessContext ctx) {
        return Collections.singleton(new I03Process(ctx));
    }

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

    /**
     * Compute all annual indices for I03 indicator.
     * TODO : multi-thread (One process per year) ?
     */
    private final class I03Process extends Process {

        public I03Process(final ProcessContext pctx) {
            super(pctx);
        }

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

        @Override
        protected Set<? extends Index> call() throws Exception {
            updateTitle("Calcul piézomètre");
            updateMessage("Analyse des données");
            final HashSet<Index> indices = new HashSet<>();
            final ArrayList<P03Statement> data = new ArrayList<>(ctx.getData().getItems());
            data.sort(I03::compare);
            if (data.isEmpty())
                return Collections.EMPTY_SET;

            LocalDate date = data.get(0).getDate();
            int previousYear = date.getMonthValue() < Month.SEPTEMBER.getValue()? date.getYear() : date.getYear() + 1;
            int year;
            int startIndex = 0;
            updateMessage("Calcul de l'année ".concat(String.valueOf(previousYear)));
            for (int i = 1 ; i < data.size() ; i++) {
                updateProgress(i, data.size());
                date = data.get(i).getDate();
                year = date.getMonthValue() < Month.SEPTEMBER.getValue()? date.getYear() : date.getYear() + 1;
                if (previousYear < year) {
                    indices.addAll(computeYear(previousYear, data.subList(startIndex, i)));
                    startIndex = i;
                    previousYear = year;
                    updateMessage("Calcul de l'année ".concat(String.valueOf(previousYear)));
                }
            }

            if (startIndex < data.size() -1) {
                indices.addAll(computeYear(previousYear, data.subList(startIndex, data.size())));
            }

            return indices;
        }
    }

    /**
     * Compute all hygrometric indices for a year.
     * /!\ Input list MUST CONTAIN ONLY THE TARGET YEAR DATA !
     * @param year Year to compute.
     * @param yearStatements data of the year to compute.
     * @return A set of hygrometric indices.
     */
    private Collection<Index> computeYear(final int year, final List<P03Statement> yearData) {
        final float[] heights = new float[yearData.size()];
        for (int i = 0 ; i < heights.length ; i++) {
            heights[i] = yearData.get(i).getHeight();
        }

        Arrays.sort(heights);
        final ArrayList<Index> result = new ArrayList<>(9);
        result.add(minSpi.createIndex(heights[0], year));
        result.add(fdSpi.createIndex(RhomeoCore.quantile(heights, 0.10f), year));
        result.add(fqSpi.createIndex(RhomeoCore.quantile(heights, 0.25f), year));
        result.add(medianeSpi.createIndex(RhomeoCore.quantile(heights, 0.5f), year));
        result.add(tqSpi.createIndex(RhomeoCore.quantile(heights, 0.75f), year));
        result.add(tdSpi.createIndex(RhomeoCore.quantile(heights, 0.90f), year));
        result.add(maxSpi.createIndex(heights[heights.length - 1], year));

        return result;
    }

    /**
     * Sort statement by date.
     * @param first First term in the comparison.
     * @param second Second term of the comparison.
     * @return comparison result.
     */
    private static int compare(final P03Statement first, P03Statement second) {
        if (first.getDate()== null && second.getDate() == null) {
            return 0;
        } else if (first.getDate() == null) {
            return 1;
        } else if (second.getDate() == null) {
            return -1;
        } else return first.getDate().compareTo(second.getDate());
    }
}
