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

//import com.sun.javafx.collections.annotations.ReturnsUnmodifiableCollection;

import javafx.beans.binding.BooleanBinding;
import javafx.beans.value.ObservableStringValue;
import javafx.beans.value.ObservableValue;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;

import java.io.File;
import java.util.regex.Pattern;

/**
 * User: twalcari
 * Date: 6/4/2014
 * Time: 17:18
 */
public class BindingsUtil {
    public static BooleanBinding instanceOfBinding(final ObservableValue observableValue, final Class clazz) {
        if (observableValue == null)
            throw new NullPointerException("ObservableValue cannot be null");
        if (clazz == null) {
            throw new NullPointerException("Class cannot be null");
        }

        return new BooleanBinding() {
            {
                super.bind(observableValue);
            }

            @Override
            public void dispose() {
                super.unbind(observableValue);
            }

            @Override
            protected boolean computeValue() {
                return clazz.isInstance(observableValue.getValue());
            }

            @Override
//            @ReturnsUnmodifiableCollection
            public ObservableList<?> getDependencies() {
                return FXCollections.singletonObservableList(observableValue);
            }
        };
    }

    public static BooleanBinding matchesRegexBinding(final ObservableStringValue observableStringValue, final Pattern pattern) {
        return new BooleanBinding() {
            {
                super.bind(observableStringValue);
            }

            @Override
            protected boolean computeValue() {
                return pattern.matcher(observableStringValue.get()).matches();
            }
        };
    }


    public static BooleanBinding isValidNewFileName(final ObservableStringValue observableStringValue) {
        return new BooleanBinding() {

            {
                super.bind(observableStringValue);
            }

            @Override
            protected boolean computeValue() {
                final String value = observableStringValue.get();
                if (value == null) return false;
                File file = new File(value);
                return (file.getParentFile() != null && file.getParentFile().exists());
            }
        };
    }
}
