package ctbrec.ui.action;

import java.io.IOException;
import java.util.Optional;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import ctbrec.Config;
import ctbrec.Model;
import ctbrec.ui.JavaFxModel;
import ctbrec.ui.controls.Dialogs;
import javafx.scene.Cursor;
import javafx.scene.Node;
import javafx.scene.control.TableView;

public class EditNotesAction {
    private static final Logger LOG = LoggerFactory.getLogger(EditNotesAction.class);

    private Node source;
    private Model model;
    private TableView<JavaFxModel> table;

    public EditNotesAction(Node source, Model selectedModel, TableView<JavaFxModel> table) {
        this.source = source;
        this.model = selectedModel;
        this.table = table;
    }

    public void execute() {
        source.setCursor(Cursor.WAIT);
        String notes = Config.getInstance().getSettings().modelNotes.getOrDefault(model.getUrl(), "");
        Optional<String> newNotes = Dialogs.showTextInput(source.getScene(), "Model Notes", "Notes for " + model.getName(), notes);
        newNotes.ifPresent(n -> {
            if (!n.trim().isEmpty()) {
                Config.getInstance().getSettings().modelNotes.put(model.getUrl(), n);
            } else {
                Config.getInstance().getSettings().modelNotes.remove(model.getUrl());
            }
            try {
                Config.getInstance().save();
            } catch (IOException e) {
                LOG.warn("Couldn't save config", e);
            }
        });
        table.refresh();
        source.setCursor(Cursor.DEFAULT);
    }
}
