package be.iminds.ilabt.jfed.experimenter_gui.slice.ribbon_tabs;

import be.iminds.ilabt.jfed.experimenter_gui.slice.ExperimentViewController;
import be.iminds.ilabt.jfed.experimenter_gui.slice.ExperimentViewControllerTab;
import be.iminds.ilabt.jfed.experimenter_gui.ui.ribbon.RibbonTab;
import javafx.application.Platform;
import javafx.beans.InvalidationListener;
import javafx.beans.WeakInvalidationListener;
import javafx.beans.property.ObjectProperty;
import javafx.beans.property.SimpleObjectProperty;

/**
 * User: twalcari
 * Date: 7/1/2014
 * Time: 11:17
 */
public abstract class SliceRibbonTab extends RibbonTab {
    protected final ObjectProperty<ExperimentViewController> activeExperimentViewController =
            new SimpleObjectProperty<>();

    public ExperimentViewController getActiveExperimentViewController() {
        return activeExperimentViewController.get();
    }

    public void setActiveExperimentViewController(ExperimentViewController activeExperimentViewController) {
        this.activeExperimentViewController.set(activeExperimentViewController);
    }

    public ObjectProperty<ExperimentViewController> activeExperimentViewControllerProperty() {
        return activeExperimentViewController;
    }


    private void updateTabStyle() {
        ExperimentViewControllerTab.TabStyle.updateTabStyle(SliceRibbonTab.this,
                activeExperimentViewController.get().getExperiment().getExperimentState());
    }

    //instance initializer
    {
        final InvalidationListener sliceStateInvalidationListener = observable -> Platform.runLater(this::updateTabStyle);

        final WeakInvalidationListener weakSliceStateInvalidationListener =
                new WeakInvalidationListener(sliceStateInvalidationListener);


        activeExperimentViewControllerProperty().addListener((observable, oldValue, newValue) -> {
            if (oldValue != null) {
                oldValue.getExperiment().experimentStateProperty().removeListener(weakSliceStateInvalidationListener);
            }

            if (newValue != null) {
                Platform.runLater(SliceRibbonTab.this::updateTabStyle);
                newValue.getExperiment().experimentStateProperty().addListener(weakSliceStateInvalidationListener);

            }
        });
    }
}
