package be.iminds.ilabt.jfed.util;

import javafx.collections.FXCollections;
import javafx.collections.ListChangeListener;
import javafx.collections.ObservableList;

/**
 * JFedJavaFXBindings
 */
public class JFedJavaFXBindings {
    private JFedJavaFXBindings() {
    }

    /**
     * order is not important!
     */
    public static <T> ObservableList<T> union(ObservableList<T>... args) {
        final ObservableList<T> res = FXCollections.observableArrayList();

        //add initial list
        for (ObservableList<T> arg : args) {
            arg.forEach(res::add);
        }

        //update on changes
        ListChangeListener<T> changeListener = change -> {
            while (change.next()) {
                if (change.wasAdded())
                    change.getAddedSubList().forEach(res::add);
                if (change.wasRemoved())
                    change.getRemoved().forEach(res::remove);
            }
        };

        for (ObservableList<T> arg : args) {
            arg.addListener(changeListener);
        }

        return res;
    }
}
