package be.iminds.ilabt.jfed.experimenter_gui.gts_editor;

import be.iminds.ilabt.jfed.experimenter_gui.gts_editor.events.ShowGTSEditorEvent;
import be.iminds.ilabt.jfed.experimenter_gui.ui.GTSEditorTabHost;
import com.google.common.eventbus.Subscribe;

import javax.inject.Inject;
import javax.inject.Singleton;
import java.util.Optional;

/**
 * User: twalcari
 * Date: 5/22/2015
 * Time: 14:12
 */
@Singleton
public class GTSEditorEventHandler {

    private final GTSEditorTabFactory gtsEditorTabFactory;
    private final GTSEditorTabHost gtsEditorTabHost;

    @Inject
    public GTSEditorEventHandler(GTSEditorTabFactory gtsEditorTabFactory, GTSEditorTabHost gtsEditorTabHost) {
        this.gtsEditorTabFactory = gtsEditorTabFactory;
        this.gtsEditorTabHost = gtsEditorTabHost;
    }


    @Subscribe
    public void handleShowGTSEditorEvent(ShowGTSEditorEvent event) {
        Optional<GTSEditorTab> existingTab = gtsEditorTabHost.getGTSEditorTabs().stream()
                .filter(tab -> tab.getGtsEditor().getEditableGtsDsl() == event.getEditableGtsDsl())
                .findAny();

        if (existingTab.isPresent()) {
            gtsEditorTabHost.showGTSEditorTab(existingTab.get());
            return;
        }

        GTSEditorTab newTab =
                gtsEditorTabFactory.createExperimentEditorTab(event.getEditableGtsDsl());

        gtsEditorTabHost.addGTSEditorTab(newTab);
        gtsEditorTabHost.showGTSEditorTab(newTab);

    }
}
