package org.javafxdata.control.cell;

import javafx.event.EventHandler;
import javafx.scene.control.Cell;
import javafx.scene.control.TextField;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyEvent;
import javafx.util.Callback;

class TextFieldCell {

    static <T> void updateItem(Cell<T> cell, TextField textField) {
        if (cell.isEmpty()) {
            cell.setText(null);
            cell.setGraphic(null);
        } else {
            if (cell.isEditing()) {
                if (textField != null) {
                    textField.setText(getItemText(cell));
                }
                cell.setText(null);
                cell.setGraphic(textField);
            } else {
                cell.setText(getItemText(cell));
                cell.setGraphic(null);
            }
        }
    }
    
    static <T> void startEdit(Cell<T> cell, TextField textField, final Callback<String, T> onCommit) {
        if (textField == null) {
            textField = createTextField(cell, onCommit);
        }
        textField.setText(getItemText(cell));
        
        cell.setText(null);
        cell.setGraphic(textField);
        
        textField.selectAll();
    }
    
    static <T> void cancelEdit(Cell<T> cell) {
        cell.setText(getItemText(cell));
        cell.setGraphic(null);
    }
    
    private static <T> TextField createTextField(final Cell<T> cell, final Callback<String, T> onCommit) {
        final TextField textField = new TextField(getItemText(cell));
        textField.setOnKeyReleased(new EventHandler<KeyEvent>() {
            @Override public void handle(KeyEvent t) {
                if (t.getCode() == KeyCode.ENTER) {
                    cell.commitEdit(onCommit.call(textField.getText()));
                } else if (t.getCode() == KeyCode.ESCAPE) {
                    cell.cancelEdit();
                }
            }
        });
        return textField;
    }
    
    private static <T> String getItemText(Cell<T> cell) {
        return cell.getItem() == null ? "" : cell.getItem().toString();
    }
}
