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

import fr.cenra.rhomeo.RhomeoTestCase;
import fr.cenra.rhomeo.api.Version;
import fr.cenra.rhomeo.api.data.DataContext;
import fr.cenra.rhomeo.api.data.Dataset;
import fr.cenra.rhomeo.api.data.Protocol;
import fr.cenra.rhomeo.api.data.Reference;
import fr.cenra.rhomeo.api.data.Site;
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.Session;
import fr.cenra.rhomeo.core.data.ReferenceManager;
import fr.cenra.rhomeo.core.data.reference.OrthopteraIndicatorReference;
import fr.cenra.rhomeo.core.data.reference.OrthopteraIndicatorReferenceDescription;
import fr.cenra.rhomeo.core.data.reference.Taxref;
import fr.cenra.rhomeo.core.data.reference.TaxrefDescription;
import fr.cenra.rhomeo.core.list.HumidZoneType;
import fr.cenra.rhomeo.core.list.OdonateZoneBio;
import fr.cenra.rhomeo.core.list.OrthoptereZoneBio;
import fr.cenra.rhomeo.core.data.site.SiteImpl;
import static fr.cenra.rhomeo.protocol.TestUtilities.createRefDataset;
import static fr.cenra.rhomeo.protocol.TestUtilities.results;
import fr.cenra.rhomeo.protocol.YearResult;
import java.beans.IntrospectionException;
import java.time.LocalDate;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
import java.util.concurrent.RunnableFuture;
import java.util.logging.Level;
import javafx.application.Platform;
import javafx.collections.ObservableMap;
import javafx.concurrent.Task;
import javafx.embed.swing.JFXPanel;
import org.junit.Assert;
import org.junit.Assume;
import org.junit.Before;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;

/**
 *
 * @author Samuel Andrés (Geomatys) <samuel.andres at geomatys.com>
 */
public class I05Test extends RhomeoTestCase {

    @Autowired
    private Session session;

    @Autowired
    @Qualifier(P05.NAME)
    private Protocol p05;

    @Autowired
    @Qualifier(I05.NAME)
    private I05 indicator;

    @Autowired
    private OrthopteraIndicatorReferenceDescription referenceDescription;

    @Autowired
    private TaxrefDescription taxrefDescription;

    @Autowired
    private AnnualRateSedimentaryDynamics indexSpi;

    @Autowired
    private AnnualPointRateSedimentaryDynamics pointIndexSpi;

    private static final LocalDate SOME_DATE = LocalDate.now();

    @Before
    public void before() throws IntrospectionException, InterruptedException, ExecutionException{

        new JFXPanel().setVisible(false);// necessary to init fx toolkit
        final ReferenceManager<OrthopteraIndicatorReference> manager = ReferenceManager.getOrCreate(referenceDescription);
        final Task<ReferenceManager> t = manager.refresh();
        t.run();
        t.get();

        Iterator<Version> it = manager.getInstalledVersions().iterator();
        Assume.assumeTrue(it.hasNext());
        final Version orthoVersion = it.next();

        final ReferenceManager<Taxref> manager2 = ReferenceManager.getOrCreate(taxrefDescription);
        final Task<ReferenceManager> t2 = manager2.refresh();
        t2.run();
        t2.get();

        it = manager2.getInstalledVersions().iterator();
        Assume.assumeTrue(it.hasNext());
        final Version taxVersion = it.next();

        final Site site = new SiteImpl(null, "countyCode", "referent", "organization", HumidZoneType.GRANDS_ESTUAIRES.getCode(), null, OrthoptereZoneBio.ALPIN_TOURBIERE.getCode(), "name", "remarks");

        session.startEdition(site, p05);
        ObservableMap<Class<Reference>, Version> refs = session.getDataContext().getReferences();
        refs.put((Class)OrthopteraIndicatorReference.class, orthoVersion);
        refs.put((Class)Taxref.class, taxVersion);
    }

    /**
     * Must retrieve dm_val.
     *
     * @throws IntrospectionException
     */
    @Test
    public void testGetIndicatorValue() throws IntrospectionException{
        final List<OrthopteraIndicatorReference> references = AbstractP05Indicator.getReferences(referenceDescription);

        Assert.assertTrue(references.size() > 0);

        for (int i = 0 ; i < Math.min(references.size(), 10) ; i++) {
            final OrthopteraIndicatorReference ref = references.get(i);
            Assert.assertEquals(ref.getDm_val(), indicator.getIndicatorValue(ref));
        }
    }

    @Test
    public void testGetDefaultIndex(){
        Assert.assertEquals(AnnualRateSedimentaryDynamics.NAME, indicator.getDefaultIndex());
    }

    @Test
    public void testGetAnnualIndexSpi(){
        Assert.assertEquals(indexSpi, ((AbstractP05Indicator) indicator).getAnnualIndexSpi());
    }

    @Test
    public void testGetAnnualPointIndexSpi(){
        Assert.assertEquals(pointIndexSpi, ((AbstractP05Indicator) indicator).getAnnualPointIndexSpi());
    }

    @Test
    public void testComputeExpected() throws IntrospectionException, ReflectiveOperationException {
        final Processor p = createProcessor(Collections.EMPTY_LIST);
        final int sum = p.sum(p.operator.getOrthopteraReferences(), OrthoptereZoneBio.ALPIN_TOURBIERE);

        // Force manual computing of expected sum, and compare it to processor result.
        int expectedSum = 0;
        final ReferenceManager<OrthopteraIndicatorReference> refManager = ReferenceManager.getOrCreate(referenceDescription);
        final Version orthoVersion = session.getDataContext().getReferences().get(OrthopteraIndicatorReference.class);
        for (final OrthopteraIndicatorReference ref : refManager.getValues(orthoVersion)) {
            if (ref.getAlpin_tb() > 0)
                expectedSum += ref.getDm_val();
        }

        Assert.assertEquals(expectedSum, sum);
    }


    ////////////////////////////////////////////////////////////////////////////
    //
    //   DATA TEST CASES
    //
    ////////////////////////////////////////////////////////////////////////////

    /**
     * Dataset test produced from database after orthoptera data insertion.
     *
     * Data query for site '93000111' (La Durance au niveau des Cassettes)
     *
     * copy (
     * select o.cd_nom as "speciesName", r.date, p.id_point_suivi as "trackingPoint", p.descriptif as "remarks"
     * from sites s join points_de_suivis p on p.id_site=s.id_site join releves r on r.id_point_suivi=p.id_point_suivi join obs_especes o on o.id_releve=r.id_releve
     * where s.id_site='93000111'
     * )
     * to '/…/testP05-1.csv' delimiter ';' csv header;
     * COPY 31
     *
     * @throws java.lang.Exception If something goes wrong.
     */
    @Test
    public void testComputing1() throws Exception {

        final String testId = "P05-1";

        final Site site = new SiteImpl(null, "05", "referent", "organization", HumidZoneType.BORDURES_COURS_EAU.getCode(), OdonateZoneBio.MED_ORIENTAL.getCode(), OrthoptereZoneBio.MED2_MARAIS_ALLUVIAL.getCode(), "name", "remarks");

        final ProcessContext pctx = new ProcessContext(createRefDataset(p05, "p05/test"+testId+".csv"), new DataContext(site, p05));

        // Compute indices. Separate them by type.
        final Set<Index<Double>> sedimentaryIndices  = new HashSet<>();

        final RunnableFuture f = new FutureTask((Callable) () -> {

            indicator.createProcesses(pctx).forEach(process -> {
                try {
                    process.run();
                    process.get().forEach(index -> {

                        if (index.getSpi()==indexSpi) {
                            sedimentaryIndices.add(index);
                        }
                    });
                } catch (Exception ex) {
                    RhomeoCore.LOGGER.log(Level.SEVERE, "Exception : ", ex);
                    Assert.fail("Proccess failed !");
                }
            });
            return "";
        });

        Platform.runLater(f);
        Assert.assertNotNull(f.get());


        // Check results. We compute only one result for multiple years.
        Assert.assertEquals("Number of sedimentary dynamics indices is wrong !", 1, sedimentaryIndices.size());


        // Load expected results
        final Map<Integer, Double> sedimentaryResults =  results("p05/result"+testId+"_"+indexSpi.getClass().getSimpleName()+".csv", YearResult.DoubleYearResult.class);

        for (final Index<Double> index : sedimentaryIndices) {
            Assert.assertEquals("Sedimentary dynamics result differs for year : ".concat(String.valueOf(index.getYear())),
                    sedimentaryResults.get(index.getYear()),
                    index.getValue(),
                    0.005
            );
        }
    }


    private Processor createProcessor(final Collection<OrthopteraStatement> statements) {
        final Dataset ds = new Dataset(p05);
        ds.getItems().addAll(statements);
        return new Processor(new ProcessContext(ds, new DataContext(new SiteImpl(null), p05)), indicator);
    }
}
