package org.javafxdata.control.cell;

import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.collections.ObservableList;
import javafx.scene.control.Cell;
import javafx.scene.control.ComboBox;
import javafx.util.Callback;

class ComboBoxCell {
    
    static <T> void updateItem(Cell<T> cell, ComboBox<T> comboBox, Callback<T, String> toString) {
        if (cell.isEmpty()) {
            cell.setText(null);
            cell.setGraphic(null);
        } else {
            if (cell.isEditing()) {
                if (comboBox != null) {
                    comboBox.getSelectionModel().select(cell.getItem());
                }
                cell.setText(null);
                cell.setGraphic(comboBox);
            } else {
                cell.setText(toString.call(cell.getItem()));
                cell.setGraphic(null);
            }
        }
    };
    
    static <T> ComboBox<T> createComboBox(final Cell<T> cell, ObservableList<T> items) {
        ComboBox<T> comboBox = new ComboBox<T>(items);
        comboBox.setMaxWidth(Double.MAX_VALUE);
        comboBox.getSelectionModel().selectedItemProperty().addListener(new ChangeListener<T>() {
            @Override public void changed(ObservableValue<? extends T> ov, T oldValue, T newValue) {
                if (cell.isEditing()) {
                    cell.commitEdit(newValue);
                }
            }
        });
        return comboBox;
    }
    
    static <T> Callback<T, String> defaultToString() {
        return new Callback<T, String>() {
            @Override public String call(T item) {
                return item == null ? "" : item.toString();
            };
        };
    }
}
