package be.iminds.ilabt.jfed.experimenter_gui.util.ui;

import javafx.beans.binding.BooleanBinding;
import javafx.collections.ListChangeListener;
import javafx.collections.ObservableList;

import java.util.function.Function;

/**
 * User: twalcari
 * Date: 11/9/2015
 * Time: 18:03
 */
public class OneTrueInListBinding<S> extends BooleanBinding {

    private final ObservableList<S> list;
    private final Function<S, BooleanBinding> conversionFunction;

    public OneTrueInListBinding(ObservableList<S> list, Function<S, BooleanBinding> conversionFunction) {
        this.list = list;
        this.conversionFunction = conversionFunction;

        list.addListener((ListChangeListener<S>) c -> {
            while (c.next()) {
                for (S item : c.getAddedSubList()) {
                    bind(conversionFunction.apply(item));
                }
                for (S item : c.getRemoved()) {
                    unbind(conversionFunction.apply(item));
                }
            }
        });
        list.forEach(item -> bind(conversionFunction.apply(item)));
    }


    @Override
    protected boolean computeValue() {
        for (S item : list) {
            if (conversionFunction.apply(item).get())
                return true;
        }

        return false;
    }
}
