package org.javafxdata.control.cell;

import javafx.scene.control.Label;
import javafx.scene.control.TableCell;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TextField;
import javafx.util.Callback;

/**
 * <p>A class containing a {@link TableCell} implementation that draws a {@link TextField}
 * node inside the cell.
 * 
 * <img src="http://www.javafxdata.org/screenshots/TextFieldCell-TableView.PNG" 
 * style="float: right; padding: 0px 0px 0px 3px;"/>
 * 
 * <p>By default, the TextFieldTableCell is rendered as a {@link Label} when not being edited, and as a TextField 
 * when in editing mode. The TextField will, by default, stretch to fill the entire table cell.
 * 
 * @param <T> The type of the elements contained within the TableColumn.
 * @author <a href="http://www.jonathangiles.net">Jonathan Giles</a>
 */
public class TextFieldTableCell<S,T> extends TableCell<S,T> {
    private TextField textField;
    
    private final Callback<String, T> onCommit;

    /**
     * Creates a TextFieldTableCell that provides a {@link TextField} when put into editing mode that allows 
     * editing of the cell content. This method will work on any TableColumn instance, 
     * regardless of its generic type. However, to enable this, a {@link Callback} must be provided that
     * will convert the given String (from what the user typed in) into an instance of type T. This
     * item will then be passed along to the {@link TableColumn#onEditCommitProperty()} callback.
     * 
     * @param onCommit A {@link Callback} that can convert the given String (from what the user typed in) 
     *      into an instance of type T.
     */
    public TextFieldTableCell(Callback<String, T> onCommit) {
        this.onCommit = onCommit;
    }
    
    /** {@inheritDoc} */
    @Override public void startEdit() {
        if (! isEditable() || ! getTableView().isEditable() || ! getTableColumn().isEditable()) {
            return;
        }
        super.startEdit();
        TextFieldCell.startEdit(this, textField, onCommit);
    }

    /** {@inheritDoc} */
    @Override public void cancelEdit() {
        super.cancelEdit();
        TextFieldCell.cancelEdit(this);
    }
    
    /** {@inheritDoc} */
    @Override public void updateItem(T item, boolean empty) {
        super.updateItem(item, empty);
        TextFieldCell.updateItem(this, textField);
    }
}