package be.iminds.jfed.gts_highlevel.jobs.gts_parts;

import be.iminds.ilabt.jfed.experiment.ExperimentPartsContainer;
import be.iminds.jfed.gts_highlevel.controller.GtsModel;
import be.iminds.jfed.gts_highlevel.model.GtsXmlProject;
import javafx.beans.property.ObjectProperty;
import javafx.beans.property.SimpleObjectProperty;
import javafx.collections.MapChangeListener;

import java.util.Objects;

/**
 * User: twalcari
 * Date: 2/4/2016
 * Time: 10:41
 */
public class GtsExperimentPartsContainer implements ExperimentPartsContainer {

    private final ObjectProperty<GtsXmlProject> project = new SimpleObjectProperty<>();
    private final boolean destroyOnTermination;

    public GtsExperimentPartsContainer(GtsXmlProject project, boolean destroyOnTermination, GtsModel model) {
        this.project.set(project);
        this.destroyOnTermination = destroyOnTermination;

        new ProjectChangeListener(project, model);
    }

    @Override
    public String getName() {
        return null;
    }

    @Override
    public boolean shouldBeDestroyedOnTermination() {
        return destroyOnTermination;
    }

    public GtsXmlProject getGtsProject() {
        return project.get();
    }

    private class ProjectChangeListener implements MapChangeListener<String, GtsXmlProject> {
        private final String projectId;
        private final GtsModel model;

        private ProjectChangeListener(GtsXmlProject project, GtsModel model) {
            this.projectId = project.getId();
            this.model = model;

            this.model.getProjects().addListener(this);

        }


        @Override
        public void onChanged(Change<? extends String, ? extends GtsXmlProject> change) {
            if (Objects.equals(projectId, change.getKey())) {
                if (change.getValueAdded() != null) {
                    GtsExperimentPartsContainer.this.project.setValue(change.getValueAdded());
                } else {
                    GtsExperimentPartsContainer.this.project.setValue(null);
                    model.getProjects().removeListener(this); // stop listening, as project has been removed
                }
            }
        }
    }
}
