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

import fr.cenra.rhomeo.api.data.DataContext;
import fr.cenra.rhomeo.api.data.Dataset;
import fr.cenra.rhomeo.api.data.Statement;
import fr.cenra.rhomeo.api.data.TrackingPoint;
import fr.cenra.rhomeo.api.result.Index;
import java.io.Externalizable;
import java.io.Serializable;
import java.util.function.Predicate;
import javafx.beans.Observable;
import javafx.beans.property.ObjectProperty;
import javafx.beans.property.SimpleObjectProperty;
import javax.validation.constraints.NotNull;

import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.collections.ObservableSet;
import javafx.collections.SetChangeListener;
import org.apache.sis.util.ArgumentChecks;

/**
 * Contains all source needed for {@link Index} processing.
 *
 * IMPORTANT : Application attempts to save restore state of this object in case
 * of unexpected shutdown. For the {@link #getFilter() } property to be saved,
 * it MUST be {@link Serializable} or {@link Externalizable}.
 *
 * @author Alexis Manin (Geomatys)
 */
public class ProcessContext {

    private final Dataset source;
    private final DataContext dataCtx;
    private final ObservableSet<Indicator> targetIndicators = FXCollections.observableSet();

    private Dataset processData;

    /**
     * A filter which allow user to specify a filter for source to take in
     * account.
     */
    private final ObjectProperty<Predicate<? extends Statement>> filterProperty = new SimpleObjectProperty<>(this, "filter", null);

    public ProcessContext(Dataset data, DataContext dataCtx) {
        ArgumentChecks.ensureNonNull("Input data", data);
        ArgumentChecks.ensureNonNull("Input data context", dataCtx);
        this.source = data;
        this.dataCtx = dataCtx;
        targetIndicators.addListener((SetChangeListener) this::indicatorsChanged);
        filterProperty.addListener(this::filterChanged);
    }

    /**
     * Dataset to use for indicator computing. It contains imported data that
     * has been selected by user for processing.
     *
     * Note : User selection is reflected by {@link #filterProperty}. But if it
     * changes, previously returned dataset won't be updated. To get an up to
     * date dataset, you must acquire a new dataset by calling this method
     * again.
     *
     * @return A dataset built from user selected data. Every time this
     * method is called, the same dataset is returned, until {@link #filterProperty()}
     * change. At this time a new dataset is generated, updating contained data
     * to match new filter.
     */
    @NotNull
    public synchronized Dataset getData() {
        if (processData == null) {
            if (filterProperty.get() == null)
                processData = source;
            else {
                processData = new Dataset(source.getProtocol());
                processData.getItems().addAll(source.getItems().filtered(filterProperty.get()));
            }
        }

        return processData;
    }

    /**
     * Return data seized by user as total dataset. This dataset should not be
     * used for processing, as it represents all data imported, not the
     * selection made after it.
     *
     * WARNING : Do not use this dataset for processing indicators. Use {@link #getData()
     * }
     * instead.
     *
     * @return Dataset which has been used for building process data.
     */
    @NotNull
    public Dataset getSourceDataset() {
        return source;
    }

    /**
     *
     * @return Seizure context. Contains chosen site and protocol for computing.
     */
    @NotNull
    public DataContext getDataCtx() {
        return dataCtx;
    }

    /**
     *
     * @return a set of tracking points, never {@code null}.
     */
    @NotNull
    public ObservableList<TrackingPoint> getTrackingPoints() {
        return FXCollections.unmodifiableObservableList(getData().getTrackingPoints());
    }

    @NotNull
    public ObservableSet<Indicator> getIndicators() {
        return targetIndicators;
    }

    /**
     * Allow user to filter source dataset. The filter will be applied when
     * calling {@link #getData() }. It serves to decimate data used by indicator
     * processes.
     *
     * @return Currently configured filter, or null if no filter is defined.
     */
    public Predicate<? extends Statement> getFilter() {
        return filterProperty.get();
    }

    /**
     * Allow user to specify a filter to apply on top of tracking point
     * decimation. If any, previous, configured filter is completely forgotten
     * after this call. To chain previously configured filter with your new one,
     * you can do something like :
     * {@code
     * final Predicate myFilter = createFilter(); // Prepare your stuff
     * final Predicate previous = processContext.getFilter();
     * processContext.setAdditionalFilter(previous.andThen(myFilter));
     * }
     *
     * @param filter Filter to configure for current processing context.
     */
    public void setFilter(Predicate<? extends Statement> filter) {
        this.filterProperty.set(filter);
    }

    public ObjectProperty<Predicate<? extends Statement>> filterProperty() {
        return filterProperty;
    }

    /**
     * A listener which check added values for {@link #targetIndicators}. It
     * automatically remove indicators not compatible with source site.
     *
     * @param c
     */
    private void indicatorsChanged(final SetChangeListener.Change<Indicator> c) {
        if (c.wasAdded() && !c.getElementAdded().getZoneTypeCodes().contains(getDataCtx().getSite().getZoneType())) {
            c.getSet().remove(c.getElementAdded());
        }
    }

    /**
     * Trigger data refresh when filter property change. The process data will
     * be regenerated on next call to {@link #getData() }
     *
     * @param obs
     * @param oldFilter
     * @param newFilter
     */
    private synchronized void filterChanged(final Observable obs) {
        processData = null;
    }
}
