package be.iminds.ilabt.jfed.util;

import javafx.scene.control.Label;
import javafx.scene.control.ListCell;
import javafx.scene.control.ListView;
import javafx.util.Callback;
import javafx.util.StringConverter;

/**
 * StringConverterListCell
 */
public class StringConverterListCell<T> extends ListCell<T> {
    private final StringConverter<T> converter;

    private final Label label = new Label();

    public StringConverterListCell(StringConverter<T> converter) {
        this.converter = converter;
    }

    @Override
    public void updateItem(final T item, boolean empty) {
        super.updateItem(item, empty);

        if (item == null) {
            label.setText("");
            setGraphic(null);
        } else {
            label.setText(converter.toString(item));
            setGraphic(label);
        }
    }

    public static <T> Callback<ListView<T>, ListCell<T>> getListViewCellFactory(StringConverter<T> converter) {
        return listView -> new StringConverterListCell<>(converter);
    }
}
