/* 
 *  AgentNotesTab.java
 * 
 *  Copyright 2016 Avaya Inc. All Rights Reserved.
 * 
 *  Usage of this source is bound to the terms described
 *  in AvayaLicenseSDK.rtf.
 * 
 *  Avaya - Confidential & Proprietary. Use pursuant to your signed agreement
 *  or Avaya Policy
 * 
 */
package com.avaya.ccs.javafxrefclient;

import java.util.Optional;
import javafx.application.Platform;
import javafx.beans.property.ReadOnlyObjectWrapper;
import javafx.beans.value.ObservableValue;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.scene.control.Button;
import javafx.scene.control.ButtonBar;
import javafx.scene.control.ButtonType;
import javafx.scene.control.Dialog;
import javafx.scene.control.Label;
import javafx.scene.control.Tab;
import javafx.scene.control.TableCell;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.TextField;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.HBox;
import javafx.scene.text.Text;
import javafx.util.Callback;

public class AgentNotesTab {

    private final Tab tab;
    private final ObservableList<String> agentNotesList = FXCollections.observableArrayList();
    private TableView<String> agentNotesTable = new TableView<String>();
    private final String BLANKAGENTNOTES = "no notes to display";
    private final InteractionExecutor interactionExe;
    private final InteractionDataGUI gui;
    private static final Logger LOG = Logger.getLogger(AgentNotesTab.class);

    public AgentNotesTab(InteractionExecutor interactionExe, InteractionDataGUI gui) {
        this.interactionExe = interactionExe;
        this.gui = gui;

        createAgentNotesTable();
        tab = new Tab();
        tab.setText("Agent Notes");
        tab.setClosable(false);
        BorderPane agentNotesPane = new BorderPane();
        agentNotesPane.setCenter(agentNotesTable);
        HBox buttons = new HBox();

        Button refresh = new Button("Refresh");
        refresh.getStyleClass().add("intrinsicButton");
        refresh.setOnAction((ActionEvent t) -> {
            String id = gui.getCurrentItemSelection().getId();
            LOG.info("RefreshButton() ID:"+ id);
            interactionExe.refreshAgentNotes(id);
        });

        Button add = new Button("Add");
        add.getStyleClass().add("intrinsicButton");
        add.setOnAction((ActionEvent t) -> {
            LOG.info("AddButton()");
            addAgentNoteDialog();
        });

        buttons.getChildren().addAll(refresh, add);
        agentNotesPane.setBottom(buttons);

        tab.setContent(agentNotesPane);
        tab.setDisable(true);
    }

    private void createAgentNotesTable() {
        agentNotesTable.setEditable(false);
        agentNotesTable.setPlaceholder(new Label(BLANKAGENTNOTES));
        TableColumn<String, String> note = new TableColumn<String, String>("Notes");

        note.setCellValueFactory(new Callback<TableColumn.CellDataFeatures<String, String>, ObservableValue<String>>() {
            @Override
            public ObservableValue<String> call(TableColumn.CellDataFeatures<String, String> p) {
                return new ReadOnlyObjectWrapper<String>(p.getValue());
            }
        });

        note.setCellFactory(new Callback<TableColumn<String, String>, TableCell<String, String>>() {
            @Override
            public TableCell<String, String> call(TableColumn<String, String> param) {
                final TableCell<String, String> cell = new TableCell<String, String>() {
                    private Text text;

                    @Override
                    public void updateItem(String item, boolean empty) {
                        super.updateItem(item, empty);
                        if (!isEmpty()) {
                            text = new Text(item);
                            text.wrappingWidthProperty().bind(getTableColumn().widthProperty().subtract(2));
                            setGraphic(text);
                        }
                    }
                };
                return cell;
            }
        });

        agentNotesTable.setColumnResizePolicy(TableView.CONSTRAINED_RESIZE_POLICY);
        agentNotesTable.setItems(agentNotesList);
        agentNotesTable.getColumns().add(note);
        agentNotesTable.setSelectionModel(null);
    }

    private void addAgentNoteDialog() {
        Dialog<String> dialog = new Dialog<>();
        dialog.setTitle("Add Agent Note");

        ButtonType okButtonType = new ButtonType("Save", ButtonBar.ButtonData.OK_DONE);
        dialog.getDialogPane().getButtonTypes().addAll(okButtonType, ButtonType.CANCEL);

        GridPane grid = new GridPane();
        grid.getStyleClass().add("dialog");

        TextField noteTextField = new TextField();

        grid.add(new Label("New Note:"), 0, 0);
        grid.add(noteTextField, 1, 0);

        dialog.getDialogPane().setContent(grid);
        dialog.setResultConverter(dialogButton -> {
            if (dialogButton == okButtonType) {
                return noteTextField.getText();
            }
            return null;
        });

        Platform.runLater(() -> noteTextField.requestFocus());
        Optional<String> result = dialog.showAndWait();

        result.ifPresent(noteValue -> {
            String methodName = "addAgentNoteDialog() ";
            LOG.trace(methodName + "Note:" + noteValue);
            interactionExe.addAgentNote(gui.getCurrentItemSelection().getId(), noteValue);
        });
    }

    public Tab getTab() {
        return tab;
    }

    void update(InteractionDataI data) {
        this.tab.setDisable(!data.canAddAgentNote()); 
        agentNotesList.clear();
        agentNotesTable.refresh();
        agentNotesList.addAll(data.getAgentNotes());
    }
}
