package be.iminds.ilabt.jfed.experiment.util;

import be.iminds.ilabt.jfed.experiment.Experiment;
import be.iminds.ilabt.jfed.experiment.ExperimentPart;
import be.iminds.ilabt.jfed.highlevel.model.Slice;
import be.iminds.ilabt.jfed.util.ExecuteOnNotNull;
import javafx.application.Platform;
import javafx.beans.binding.ObjectBinding;
import javafx.collections.ListChangeListener;
import javafx.collections.WeakListChangeListener;

/**
 * User: twalcari
 * Date: 8/18/2016
 * Time: 10:24
 */
public class NextExperimentExpirationBinding extends ObjectBinding<NextExperimentExpiration> {

    private final Experiment experiment;

    @SuppressWarnings("FieldCanBeLocal")
    private final ListChangeListener<ExperimentPart> experimentPartsListChangeListener = c -> {
        while (c.next()) {
            c.getAddedSubList().forEach(part -> bind(part.expirationTimeProperty()));
            c.getRemoved().forEach(part -> unbind(part.expirationTimeProperty()));
        }

        Platform.runLater(this::invalidate);
    };

    public NextExperimentExpirationBinding(Experiment experiment) {
        this.experiment = experiment;

        experiment.getParts().forEach(part -> bind(part.expirationTimeProperty()));
        experiment.getParts().addListener(new WeakListChangeListener<>(experimentPartsListChangeListener));

        new ExecuteOnNotNull<Slice>(experiment.sliceProperty()) {
            @Override
            public void run() {
                assert experiment.getSlice() != null;
                bind(experiment.getSlice().expirationDateProperty());
            }
        };
    }



    @Override
    protected NextExperimentExpiration computeValue() {
        if (experiment.getSlice() == null)
            return null;
        else
            return new NextExperimentExpiration(experiment);
    }

    
}
