package ctbrec.ui.tabs;

import static ctbrec.Recording.State.*;
import static ctbrec.SubsequentAction.*;

import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.time.Instant;
import java.time.LocalDate;
import java.time.ZoneId;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;
import java.util.function.Function;
import java.util.stream.Collectors;

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

import ctbrec.Config;
import ctbrec.Model;
import ctbrec.Recording;
import ctbrec.StringUtil;
import ctbrec.SubsequentAction;
import ctbrec.recorder.Recorder;
import ctbrec.sites.Site;
import ctbrec.ui.AutosizeAlert;
import ctbrec.ui.DesktopIntegration;
import ctbrec.ui.JavaFxModel;
import ctbrec.ui.PreviewPopupHandler;
import ctbrec.ui.StreamSourceSelectionDialog;
import ctbrec.ui.action.EditNotesAction;
import ctbrec.ui.action.FollowAction;
import ctbrec.ui.action.OpenRecordingsDir;
import ctbrec.ui.action.PauseAction;
import ctbrec.ui.action.PlayAction;
import ctbrec.ui.action.ResumeAction;
import ctbrec.ui.action.StopRecordingAction;
import ctbrec.ui.controls.DateTimeCellFactory;
import ctbrec.ui.controls.Dialogs;
import ctbrec.ui.controls.SearchBox;
import ctbrec.ui.controls.autocomplete.AutoFillTextField;
import ctbrec.ui.controls.autocomplete.ObservableListSuggester;
import javafx.application.Platform;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringPropertyBase;
import javafx.beans.value.ChangeListener;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.concurrent.ScheduledService;
import javafx.concurrent.Task;
import javafx.concurrent.WorkerStateEvent;
import javafx.event.ActionEvent;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.control.Alert;
import javafx.scene.control.Button;
import javafx.scene.control.ContextMenu;
import javafx.scene.control.DatePicker;
import javafx.scene.control.Label;
import javafx.scene.control.MenuItem;
import javafx.scene.control.RadioButton;
import javafx.scene.control.ScrollPane;
import javafx.scene.control.SelectionMode;
import javafx.scene.control.Tab;
import javafx.scene.control.TableCell;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableColumn.CellEditEvent;
import javafx.scene.control.TableColumn.SortType;
import javafx.scene.control.TableRow;
import javafx.scene.control.TableView;
import javafx.scene.control.TextField;
import javafx.scene.control.ToggleGroup;
import javafx.scene.control.Tooltip;
import javafx.scene.control.cell.CheckBoxTableCell;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.control.cell.TextFieldTableCell;
import javafx.scene.input.Clipboard;
import javafx.scene.input.ClipboardContent;
import javafx.scene.input.ContextMenuEvent;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyEvent;
import javafx.scene.input.MouseButton;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.FlowPane;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Priority;
import javafx.util.Callback;
import javafx.util.Duration;
import javafx.util.StringConverter;
import javafx.util.converter.NumberStringConverter;

public class RecordedModelsTab extends Tab implements TabSelectionListener {
    private static final Logger LOG = LoggerFactory.getLogger(RecordedModelsTab.class);

    private ReentrantLock lock = new ReentrantLock();
    private ScheduledService<List<JavaFxModel>> updateService;
    private Recorder recorder;
    private List<Site> sites;
    private volatile boolean cellEditing = false;

    FlowPane grid = new FlowPane();
    ScrollPane scrollPane = new ScrollPane();
    TableView<JavaFxModel> table = new TableView<>();
    ObservableList<JavaFxModel> observableModels = FXCollections.observableArrayList();
    ObservableList<JavaFxModel> filteredModels = FXCollections.observableArrayList();
    ContextMenu popup;

    Label modelLabel = new Label("Model");
    AutoFillTextField model;
    Button addModelButton = new Button("Record");
    Button pauseAll = new Button("Pause All");
    Button resumeAll = new Button("Resume All");
    TextField filter;

    public RecordedModelsTab(String title, Recorder recorder, List<Site> sites) {
        super(title);
        this.recorder = recorder;
        this.sites = sites;
        createGui();
        setClosable(false);
        initializeUpdateService();
    }

    @SuppressWarnings("unchecked")
    private void createGui() {
        grid.setPadding(new Insets(5));
        grid.setHgap(5);
        grid.setVgap(5);

        scrollPane.setContent(grid);
        scrollPane.setFitToHeight(true);
        scrollPane.setFitToWidth(true);
        BorderPane.setMargin(scrollPane, new Insets(5));


        table.setEditable(true);
        table.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE);
        PreviewPopupHandler previewPopupHandler = new PreviewPopupHandler(table);
        table.setRowFactory(tableview -> {
            TableRow<JavaFxModel> row = new TableRow<>();
            row.addEventHandler(MouseEvent.ANY, previewPopupHandler);
            return row;
        });
        TableColumn<JavaFxModel, String> preview = new TableColumn<>("🎥");
        preview.setPrefWidth(35);
        preview.setCellValueFactory(cdf -> new SimpleStringProperty("  ▶  "));
        preview.setEditable(false);
        preview.setId("preview");
        if(!Config.getInstance().getSettings().livePreviews) {
            preview.setVisible(false);
        }
        TableColumn<JavaFxModel, String> name = new TableColumn<>("Model");
        name.setPrefWidth(200);
        name.setCellValueFactory(new PropertyValueFactory<JavaFxModel, String>("displayName"));
        name.setCellFactory(new ClickableCellFactory<>());
        name.setEditable(false);
        name.setId("name");
        TableColumn<JavaFxModel, String> url = new TableColumn<>("URL");
        url.setCellValueFactory(new PropertyValueFactory<JavaFxModel, String>("url"));
        url.setCellFactory(new ClickableCellFactory<>());
        url.setPrefWidth(400);
        url.setEditable(false);
        url.setId("url");
        TableColumn<JavaFxModel, Boolean> online = new TableColumn<>("Online");
        online.setCellValueFactory(cdf -> cdf.getValue().getOnlineProperty());
        online.setCellFactory(CheckBoxTableCell.forTableColumn(online));
        online.setPrefWidth(100);
        online.setEditable(false);
        online.setId("online");
        TableColumn<JavaFxModel, Boolean> recording = new TableColumn<>("Recording");
        recording.setCellValueFactory(cdf -> cdf.getValue().getRecordingProperty());
        recording.setCellFactory(CheckBoxTableCell.forTableColumn(recording));
        recording.setPrefWidth(100);
        recording.setEditable(false);
        recording.setId("recording");
        TableColumn<JavaFxModel, Boolean> paused = new TableColumn<>("Paused");
        paused.setCellValueFactory(cdf -> cdf.getValue().getPausedProperty());
        paused.setCellFactory(CheckBoxTableCell.forTableColumn(paused));
        paused.setPrefWidth(100);
        paused.setEditable(true);
        paused.setId("paused");
        TableColumn<JavaFxModel, Number> priority = new TableColumn<>("Priority");
        priority.setCellValueFactory(param -> param.getValue().getPriorityProperty());
        priority.setCellFactory(new PriorityCellFactory());
        priority.setPrefWidth(90);
        priority.setEditable(true);
        priority.setOnEditStart(e -> cellEditing = true);
        priority.setOnEditCommit(this::onUpdatePriority);
        priority.setOnEditCancel(e -> cellEditing = false);
        priority.setId("priority");
        TableColumn<JavaFxModel, Instant> lastSeen = new TableColumn<>("last seen");
        lastSeen.setCellValueFactory(cdf -> cdf.getValue().lastSeenProperty());
        lastSeen.setCellFactory(new DateTimeCellFactory<JavaFxModel>());
        lastSeen.setPrefWidth(150);
        lastSeen.setEditable(false);
        lastSeen.setId("lastSeen");
        TableColumn<JavaFxModel, Instant> lastRecorded = new TableColumn<>("last recorded");
        lastRecorded.setCellValueFactory(cdf -> cdf.getValue().lastRecordedProperty());
        lastRecorded.setCellFactory(new DateTimeCellFactory<JavaFxModel>());
        lastRecorded.setPrefWidth(150);
        lastRecorded.setEditable(false);
        lastRecorded.setId("lastRecorded");
        TableColumn<JavaFxModel, String> notes = new TableColumn<>("Notes");
        notes.setCellValueFactory(cdf -> {
            JavaFxModel m = cdf.getValue();
            return new StringPropertyBase() {
                @Override
                public String getName() {
                    return "Model Notes";
                }

                @Override
                public Object getBean() {
                    return null;
                }

                @Override
                public String get() {
                    String modelNotes = Config.getInstance().getModelNotes(m);
                    return modelNotes;
                }
            };
        });
        notes.setPrefWidth(400);
        notes.setEditable(false);
        notes.setId("notes");
        table.getColumns().addAll(preview, name, url, online, recording, paused, priority, lastSeen, lastRecorded, notes);
        table.setItems(observableModels);
        table.addEventHandler(ContextMenuEvent.CONTEXT_MENU_REQUESTED, event -> {
            popup = createContextMenu();
            if (popup != null) {
                popup.show(table, event.getScreenX(), event.getScreenY());
            }
            event.consume();
        });
        table.addEventHandler(MouseEvent.MOUSE_PRESSED, event -> {
            if (popup != null) {
                popup.hide();
            }
        });
        table.addEventHandler(KeyEvent.KEY_PRESSED, event -> {
            List<JavaFxModel> selectedModels = table.getSelectionModel().getSelectedItems();
            if (event.getCode() == KeyCode.DELETE) {
                stopAction(selectedModels);
            } else {
                jumpToNextModel(event.getCode());
            }
        });

        scrollPane.setContent(table);

        HBox addModelBox = new HBox(5);
        modelLabel.setPadding(new Insets(5, 0, 0, 0));
        ObservableList<String> suggestions = FXCollections.observableArrayList();
        sites.forEach(site -> suggestions.add(site.getClass().getSimpleName()));
        model = new AutoFillTextField(new ObservableListSuggester(suggestions));
        model.setPrefWidth(600);
        model.setPromptText("e.g. MyFreeCams:ModelName or an URL like https://chaturbate.com/modelname/");
        model.onActionHandler(this::addModel);
        model.setTooltip(new Tooltip("To add a model enter SiteName:ModelName\n" +
                "press ENTER to confirm a suggested site name"));
        BorderPane.setMargin(addModelBox, new Insets(5));
        addModelButton.setOnAction(this::addModel);
        addModelButton.setPadding(new Insets(5));
        addModelBox.getChildren().addAll(modelLabel, model, addModelButton, pauseAll, resumeAll);
        HBox.setMargin(pauseAll, new Insets(0, 0, 0, 20));
        pauseAll.setOnAction(this::pauseAll);
        resumeAll.setOnAction(this::resumeAll);
        pauseAll.setPadding(new Insets(5));
        resumeAll.setPadding(new Insets(5));

        HBox filterContainer = new HBox();
        filterContainer.setSpacing(0);
        filterContainer.setPadding(new Insets(0));
        filterContainer.setAlignment(Pos.CENTER_RIGHT);
        HBox.setHgrow(filterContainer, Priority.ALWAYS);
        filter = new SearchBox(false);
        filter.setPromptText("Filter");
        filter.textProperty().addListener( (observableValue, oldValue, newValue) -> {
            String q = filter.getText();
            lock.lock();
            try {
                filter(q);
            } finally {
                lock.unlock();
            }
        });
        filter.getStyleClass().remove("search-box-icon");
        filterContainer.getChildren().add(filter);
        addModelBox.getChildren().add(filterContainer);


        BorderPane root = new BorderPane();
        root.setPadding(new Insets(5));
        root.setTop(addModelBox);
        root.setCenter(scrollPane);
        setContent(root);

        restoreState();
    }

    private void jumpToNextModel(KeyCode code) {
        if (!table.getItems().isEmpty() && (code.isLetterKey() || code.isDigitKey())) {
            // determine where to start looking for the next model
            int startAt = 0;
            if (table.getSelectionModel().getSelectedIndex() >= 0) {
                startAt = table.getSelectionModel().getSelectedIndex() + 1;
                if (startAt >= table.getItems().size()) {
                    startAt = 0;
                }
            }

            String c = code.getChar().toLowerCase();
            int i = startAt;
            do {
                JavaFxModel current = table.getItems().get(i);
                if (current.getName().toLowerCase().replaceAll("[^0-9a-z]", "").startsWith(c)) {
                    table.getSelectionModel().clearAndSelect(i);
                    table.scrollTo(i);
                    break;
                }

                i++;
                if (i >= table.getItems().size()) {
                    i = 0;
                }
            } while (i != startAt);
        }
    }

    private void onUpdatePriority(CellEditEvent<JavaFxModel, Number> evt) {
        try {
            int prio = Optional.ofNullable(evt.getNewValue()).map(Number::intValue).orElse(-1);
            JavaFxModel m = evt.getRowValue();
            updatePriority(m, prio);
            table.refresh();
        } finally {
            cellEditing = false;
        }
    }

    private void updatePriority(JavaFxModel model, int priority) {
        try {
            if (priority < 0 || priority > 100) {
                String msg = "Priority has to be between 0 and 100";
                Dialogs.showError(table.getScene(), "Invalid value", msg, null);
            } else {
                model.setPriority(priority);
                recorder.priorityChanged(model.getDelegate());
            }
        } catch (InvalidKeyException | NoSuchAlgorithmException | IOException e) {
            Dialogs.showError(table.getScene(), "Couldn't update priority", e.getMessage(), e);
        }
    }

    private void addModel(ActionEvent e) {
        String input = model.getText();
        if (StringUtil.isBlank(input)) {
            return;
        }

        if (input.startsWith("http")) {
            addModelByUrl(input);
        } else {
            addModelByName(input);
        }
    }

    private void addModelByUrl(String url) {
        for (Site site : sites) {
            Model newModel = site.createModelFromUrl(url);
            if (newModel != null) {
                try {
                    recorder.startRecording(newModel);
                } catch (IOException | InvalidKeyException | NoSuchAlgorithmException | IllegalStateException e1) {
                    Dialogs.showError(getTabPane().getScene(), "Couldn't add model", "The model " + newModel.getName() + " could not be added: ", e1);
                }
                return;
            }
        }

        Dialogs.showError(getTabPane().getScene(), "Unknown URL format",
                "The URL you entered has an unknown format or the function does not support this site, yet", null);
    }

    private void addModelByName(String siteModelCombo) {
        String[] parts = siteModelCombo.trim().split(":");
        if (parts.length != 2) {
            Dialogs.showError(getTabPane().getScene(), "Wrong input format", "Use something like \"MyFreeCams:ModelName\"", null);
            return;
        }

        String siteName = parts[0];
        String modelName = parts[1];
        for (Site site : sites) {
            if (Objects.equals(siteName.toLowerCase(), site.getClass().getSimpleName().toLowerCase())) {
                try {
                    Model m = site.createModel(modelName);
                    recorder.startRecording(m);
                } catch (IOException | InvalidKeyException | NoSuchAlgorithmException | IllegalStateException e1) {
                    Dialogs.showError(getTabPane().getScene(), "Couldn't add model", "The model " + modelName + " could not be added:", e1);
                }
                return;
            }
        }

        Alert alert = new AutosizeAlert(Alert.AlertType.ERROR, getTabPane().getScene());
        alert.setTitle("Unknown site");
        alert.setHeaderText("Couldn't add model");
        alert.setContentText("The site you entered is unknown");
        alert.showAndWait();
    }

    private void pauseAll(ActionEvent evt) {
        boolean yes = Dialogs.showConfirmDialog("Pause all models", "", "Pause the recording of all models?", getTabPane().getScene());
        if (yes) {
            new PauseAction(getTabPane(), recorder.getModels(), recorder).execute();
        }
    }

    private void resumeAll(ActionEvent evt) {
        boolean yes = Dialogs.showConfirmDialog("Resume all models", "", "Resume the recording of all models?", getTabPane().getScene());
        if (yes) {
            new ResumeAction(getTabPane(), recorder.getModels(), recorder).execute();
        }
    }

    void initializeUpdateService() {
        updateService = createUpdateService();
        updateService.setPeriod(new Duration(TimeUnit.SECONDS.toMillis(2)));
        updateService.setOnSucceeded(this::onUpdateSuccess);
        updateService.setOnFailed(event -> LOG.info("Couldn't get list of models from recorder", event.getSource().getException()));
    }

    private void onUpdateSuccess(WorkerStateEvent event) {
        if (cellEditing) {
            return;
        }

        List<JavaFxModel> updatedModels = updateService.getValue();
        if (updatedModels == null) {
            return;
        }

        lock.lock();
        try {
            addOrUpdateModels(updatedModels);

            // remove old ones, which are not in the list of updated models
            for (Iterator<JavaFxModel> iterator = observableModels.iterator(); iterator.hasNext();) {
                Model oldModel = iterator.next();
                if (!updatedModels.contains(oldModel)) {
                    iterator.remove();
                }
            }
        } finally {
            lock.unlock();
        }

        filteredModels.clear();
        filter(filter.getText());
        table.sort();
    }

    private void addOrUpdateModels(List<JavaFxModel> updatedModels) {
        for (JavaFxModel updatedModel : updatedModels) {
            int index = observableModels.indexOf(updatedModel);
            if (index == -1) {
                observableModels.add(updatedModel);
                updatedModel.getPausedProperty().addListener(createPauseListener(updatedModel));
            } else {
                // make sure to update the JavaFX online property, so that the table cell is updated
                JavaFxModel oldModel = observableModels.get(index);
                oldModel.setSuspended(updatedModel.isSuspended());
                oldModel.getOnlineProperty().set(updatedModel.getOnlineProperty().get());
                oldModel.getRecordingProperty().set(updatedModel.getRecordingProperty().get());
                oldModel.lastRecordedProperty().set(updatedModel.lastRecordedProperty().get());
                oldModel.lastSeenProperty().set(updatedModel.lastSeenProperty().get());
            }
        }
    }

    private ChangeListener<Boolean> createPauseListener(JavaFxModel updatedModel) {
        return (obs, oldV, newV) -> {
            if (newV.booleanValue()) {
                if(!recorder.isSuspended(updatedModel)) {
                    pauseRecording(Collections.singletonList(updatedModel));
                }
            } else {
                if(recorder.isSuspended(updatedModel)) {
                    resumeRecording(Collections.singletonList(updatedModel));
                }
            }
        };
    }

    private void filter(String filter) {
        lock.lock();
        try {
            if (StringUtil.isBlank(filter)) {
                observableModels.addAll(filteredModels);
                filteredModels.clear();
                return;
            }

            String[] tokens = filter.split(" ");
            observableModels.addAll(filteredModels);
            filteredModels.clear();
            for (int i = 0; i < table.getItems().size(); i++) {
                StringBuilder sb = new StringBuilder();
                for (TableColumn<JavaFxModel, ?> tc : table.getColumns()) {
                    Object cellData = tc.getCellData(i);
                    if (cellData != null) {
                        String content = cellData.toString();
                        sb.append(content).append(' ');
                    }
                }
                String searchText = sb.toString();

                boolean tokensMissing = false;
                for (String token : tokens) {
                    if (!searchText.toLowerCase().contains(token.toLowerCase())) {
                        tokensMissing = true;
                        break;
                    }
                }
                if (tokensMissing) {
                    JavaFxModel filteredModel = table.getItems().get(i);
                    filteredModels.add(filteredModel);
                }
            }
            observableModels.removeAll(filteredModels);
        } finally {
            lock.unlock();
        }
    }

    private ScheduledService<List<JavaFxModel>> createUpdateService() {
        ScheduledService<List<JavaFxModel>> modelUpdateService = new ScheduledService<List<JavaFxModel>>() {
            @Override
            protected Task<List<JavaFxModel>> createTask() {
                return new Task<List<JavaFxModel>>() {
                    @Override
                    public List<JavaFxModel> call() throws InvalidKeyException, NoSuchAlgorithmException, IOException {
                        LOG.trace("Updating recorded models");
                        List<Recording> recordings = recorder.getRecordings();
                        List<Model> onlineModels = recorder.getOnlineModels();
                        return recorder.getModels()
                                .stream()
                                .map(JavaFxModel::new)
                                .peek(fxm -> {
                                    for (Recording recording : recordings) {
                                        if(recording.getStatus() == RECORDING && Objects.equals(recording.getModel(), fxm)){
                                            fxm.getRecordingProperty().set(true);
                                            break;
                                        }
                                    }

                                    for (Model onlineModel : onlineModels) {
                                        if(Objects.equals(onlineModel, fxm)) {
                                            fxm.getOnlineProperty().set(true);
                                            break;
                                        }
                                    }
                                })
                                .collect(Collectors.toList());
                    }
                };
            }
        };
        ExecutorService executor = Executors.newSingleThreadExecutor(r -> {
            Thread t = new Thread(r);
            t.setDaemon(true);
            t.setName("RecordedModelsTab UpdateService");
            return t;
        });
        modelUpdateService.setExecutor(executor);
        return modelUpdateService;
    }

    @Override
    public void selected() {
        if (updateService != null) {
            updateService.reset();
            updateService.restart();
        }
    }

    @Override
    public void deselected() {
        if (updateService != null) {
            updateService.cancel();
        }
    }

    private ContextMenu createContextMenu() {
        ObservableList<JavaFxModel> selectedModels = table.getSelectionModel().getSelectedItems();
        if (selectedModels.isEmpty()) {
            return null;
        }
        MenuItem stop = new MenuItem("Remove Model");
        stop.setOnAction(e -> stopAction(selectedModels));

        MenuItem copyUrl = new MenuItem("Copy URL");
        copyUrl.setOnAction(e -> {
            Model selected = selectedModels.get(0);
            final Clipboard clipboard = Clipboard.getSystemClipboard();
            final ClipboardContent content = new ClipboardContent();
            content.putString(selected.getUrl());
            clipboard.setContent(content);
        });

        MenuItem pauseRecording = new MenuItem("Pause Recording");
        pauseRecording.setOnAction(e -> pauseRecording(selectedModels));
        MenuItem resumeRecording = new MenuItem("Resume Recording");
        resumeRecording.setOnAction(e -> resumeRecording(selectedModels));
        MenuItem stopRecordingAt = new MenuItem("Stop Recording at Date");
        stopRecordingAt.setOnAction(e -> setStopDate(selectedModels.get(0)));
        MenuItem openInBrowser = new MenuItem("Open in Browser");
        openInBrowser.setOnAction(e -> DesktopIntegration.open(selectedModels.get(0).getUrl()));
        MenuItem openInPlayer = new MenuItem("Open in Player");
        openInPlayer.setOnAction(e -> openInPlayer(selectedModels.get(0)));
        MenuItem switchStreamSource = new MenuItem("Switch resolution");
        switchStreamSource.setOnAction(e -> switchStreamSource(selectedModels.get(0)));
        MenuItem follow = new MenuItem("Follow");
        follow.setOnAction(e -> follow(selectedModels));
        MenuItem ignore = new MenuItem("Ignore");
        ignore.setOnAction(e -> ignore(selectedModels));
        MenuItem notes = new MenuItem("Notes");
        notes.setOnAction(e -> notes(selectedModels));
        MenuItem openRecDir = new MenuItem("Open recording directory");
        openRecDir.setOnAction(e -> new OpenRecordingsDir(table, selectedModels.get(0)).execute());

        ContextMenu menu = new ContextMenu(stop);
        if (selectedModels.size() == 1) {
            menu.getItems().add(selectedModels.get(0).isSuspended() ? resumeRecording : pauseRecording);
            menu.getItems().add(stopRecordingAt);
        } else {
            menu.getItems().addAll(resumeRecording, pauseRecording);
        }
        menu.getItems().addAll(copyUrl, openInPlayer, openInBrowser, openRecDir, switchStreamSource, follow, notes, ignore);

        if (selectedModels.size() > 1) {
            copyUrl.setDisable(true);
            openInPlayer.setDisable(true);
            openInBrowser.setDisable(true);
            switchStreamSource.setDisable(true);
            notes.setDisable(true);
        }

        return menu;
    }

    private void setStopDate(JavaFxModel model) {
        DatePicker datePicker = new DatePicker();
        GridPane grid = new GridPane();
        grid.setHgap(10);
        grid.setVgap(10);
        grid.setPadding(new Insets(20, 150, 10, 10));
        grid.add(new Label("Stop at"), 0, 0);
        grid.add(datePicker, 1, 0);
        grid.add(new Label("And then"), 0, 1);
        ToggleGroup toggleGroup = new ToggleGroup();
        RadioButton pauseButton = new RadioButton("pause recording");
        pauseButton.setSelected(model.getRecordUntilSubsequentAction() == PAUSE);
        pauseButton.setToggleGroup(toggleGroup);
        RadioButton removeButton = new RadioButton("remove model");
        removeButton.setSelected(model.getRecordUntilSubsequentAction() == REMOVE);
        removeButton.setToggleGroup(toggleGroup);
        HBox row = new HBox();
        row.getChildren().addAll(pauseButton, removeButton);
        HBox.setMargin(pauseButton, new Insets(5));
        HBox.setMargin(removeButton, new Insets(5));
        grid.add(row, 1, 1);
        if (model.getRecordUntil().toEpochMilli() != Model.RECORD_INDEFINITELY) {
            LocalDate localDate = LocalDate.ofInstant(model.getRecordUntil(), ZoneId.systemDefault());
            datePicker.setValue(localDate);
        }
        boolean userClickedOk = Dialogs.showCustomInput(getTabPane().getScene(), "Stop Recording at", grid);
        if (userClickedOk) {
            SubsequentAction action = pauseButton.isSelected() ? PAUSE : REMOVE;
            LOG.info("Stop at {} and {}", datePicker.getValue(), action);
            Instant stopAt = Instant.from(datePicker.getValue().atStartOfDay().atZone(ZoneId.systemDefault()));
            model.setRecordUntil(stopAt);
            model.setRecordUntilSubsequentAction(action);
            try {
                recorder.stopRecordingAt(model.getDelegate());
            } catch (InvalidKeyException | NoSuchAlgorithmException | IOException e) {
                Dialogs.showError(getTabPane().getScene(), "Error", "Couln't set stop date", e);
            }
        }
    }

    private void ignore(ObservableList<JavaFxModel> selectedModels) {
        for (JavaFxModel fxModel : selectedModels) {
            Model modelToIgnore = fxModel.getDelegate();
            Config.getInstance().getSettings().modelsIgnored.add(modelToIgnore);
        }
        boolean removeAsWell = Dialogs.showConfirmDialog("Ignore Model", null, "Remove as well?", getTabPane().getScene());
        if (removeAsWell) {
            stopAction(selectedModels);
        }
    }

    private void follow(ObservableList<JavaFxModel> selectedModels) {
        new FollowAction(getTabPane(), new ArrayList<JavaFxModel>(selectedModels)).execute();
    }

    private void notes(ObservableList<JavaFxModel> selectedModels) {
        new EditNotesAction(getTabPane(), selectedModels.get(0), table).execute();
    }

    private void openInPlayer(JavaFxModel selectedModel) {
        new PlayAction(getTabPane(), selectedModel).execute();
    }

    private void switchStreamSource(JavaFxModel fxModel) {
        String couldntSwitchHeaderText = "Couldn't switch stream resolution";

        try {
            if (!fxModel.isOnline(true)) {
                Dialogs.showError(getTabPane().getScene(), couldntSwitchHeaderText, "The resolution can only be changed, when the model is online", null);
                return;
            }
        } catch (InterruptedException e1) {
            Thread.currentThread().interrupt();
            Dialogs.showError(getTabPane().getScene(), couldntSwitchHeaderText, "An error occured while checking, if the model is online", null);
            return;
        } catch (IOException | ExecutionException e1) {
            Dialogs.showError(getTabPane().getScene(), couldntSwitchHeaderText, "An error occured while checking, if the model is online", null);
            return;
        }

        Function<Model, Void> onSuccess = m -> {
            try {
                recorder.switchStreamSource(m);
            } catch (InvalidKeyException | NoSuchAlgorithmException | IllegalStateException | IOException e) {
                LOG.error(couldntSwitchHeaderText, e);
                showStreamSwitchErrorDialog(e);
            }
            return null;
        };
        Function<Throwable, Void> onFail = t -> {
            LOG.error(couldntSwitchHeaderText, t);
            showStreamSwitchErrorDialog(t);
            return null;
        };
        StreamSourceSelectionDialog.show(getTabPane().getScene(), fxModel.getDelegate(), onSuccess, onFail);
    }

    private void showStreamSwitchErrorDialog(Throwable throwable) {
        showErrorDialog(throwable, "Couldn't switch stream resolution", "Error while switching stream resolution");
    }

    private void showErrorDialog(Throwable throwable, String header, String msg) {
        Alert alert = new AutosizeAlert(Alert.AlertType.ERROR, getTabPane().getScene());
        alert.setTitle("Error");
        alert.setHeaderText(header);
        alert.setContentText(msg + ": " + throwable.getLocalizedMessage());
        alert.showAndWait();
    }

    private void stopAction(List<JavaFxModel> selectedModels) {
        List<Model> models = selectedModels.stream().map(JavaFxModel::getDelegate).collect(Collectors.toList());
        new StopRecordingAction(getTabPane(), models, recorder).execute(m -> Platform.runLater(() -> {
            table.getSelectionModel().clearSelection(table.getItems().indexOf(m));
            table.getItems().remove(m);
        }));
    }

    private void pauseRecording(List<JavaFxModel> selectedModels) {
        List<Model> models = selectedModels.stream().map(JavaFxModel::getDelegate).collect(Collectors.toList());
        new PauseAction(getTabPane(), models, recorder).execute();
    }

    private void resumeRecording(List<JavaFxModel> selectedModels) {
        List<Model> models = selectedModels.stream().map(JavaFxModel::getDelegate).collect(Collectors.toList());
        new ResumeAction(getTabPane(), models, recorder).execute();
    }

    public void saveState() {
        if (!table.getSortOrder().isEmpty()) {
            TableColumn<JavaFxModel, ?> col = table.getSortOrder().get(0);
            Config.getInstance().getSettings().recordedModelsSortColumn = col.getText();
            Config.getInstance().getSettings().recordedModelsSortType = col.getSortType().toString();
        }
        int columns = table.getColumns().size();
        double[] columnWidths = new double[columns];
        String[] columnIds = new String[columns];
        for (int i = 0; i < columnWidths.length; i++) {
            columnWidths[i] = table.getColumns().get(i).getWidth();
            columnIds[i] = table.getColumns().get(i).getId();
        }
        Config.getInstance().getSettings().recordedModelsColumnWidths = columnWidths;
        Config.getInstance().getSettings().recordedModelsColumnIds = columnIds;
    }

    private void restoreState() {
        restoreColumnOrder();
        restoreColumnWidths();
        restoreSorting();
    }

    private void restoreSorting() {
        String sortCol = Config.getInstance().getSettings().recordedModelsSortColumn;
        if (StringUtil.isNotBlank(sortCol)) {
            for (TableColumn<JavaFxModel, ?> col : table.getColumns()) {
                if (Objects.equals(sortCol, col.getText())) {
                    col.setSortType(SortType.valueOf(Config.getInstance().getSettings().recordedModelsSortType));
                    table.getSortOrder().clear();
                    table.getSortOrder().add(col);
                    break;
                }
            }
        }
    }

    private void restoreColumnOrder() {
        String[] columnIds = Config.getInstance().getSettings().recordedModelsColumnIds;
        ObservableList<TableColumn<JavaFxModel,?>> columns = table.getColumns();
        for (int i = 0; i < columnIds.length; i++) {
            for (int j = 0; j < table.getColumns().size(); j++) {
                if(Objects.equals(columnIds[i], columns.get(j).getId())) {
                    TableColumn<JavaFxModel, ?> col = columns.get(j);
                    columns.remove(j); // NOSONAR
                    columns.add(i, col);
                }
            }
        }
    }

    private void restoreColumnWidths() {
        double[] columnWidths = Config.getInstance().getSettings().recordedModelsColumnWidths;
        if (columnWidths != null && columnWidths.length == table.getColumns().size()) {
            for (int i = 0; i < columnWidths.length; i++) {
                table.getColumns().get(i).setPrefWidth(columnWidths[i]);
            }
        }
    }

    private class ClickableCellFactory<S, T> implements Callback<TableColumn<S, T>, TableCell<S, T>> {
        @Override
        public TableCell<S, T> call(TableColumn<S, T> param) {
            TableCell<S, T> cell = new TableCell<>() {
                @Override
                protected void updateItem(Object item, boolean empty) {
                    setText(empty ? "" : Objects.toString(item));
                }
            };

            cell.addEventFilter(MouseEvent.MOUSE_CLICKED, event -> {
                if (event.getButton() == MouseButton.PRIMARY && event.getClickCount() == 2) {
                    JavaFxModel selectedModel = table.getSelectionModel().getSelectedItem();
                    if(selectedModel != null) {
                        new PlayAction(table, selectedModel).execute();
                    }
                }
            });
            return cell;
        }
    }

    private class PriorityCellFactory implements Callback<TableColumn<JavaFxModel, Number>, TableCell<JavaFxModel, Number>> {
        @Override
        public TableCell<JavaFxModel, Number> call(TableColumn<JavaFxModel, Number> param) {
            Callback<TableColumn<JavaFxModel, Number>, TableCell<JavaFxModel, Number>> callback = TextFieldTableCell
                    .<JavaFxModel, Number> forTableColumn((StringConverter<Number>) new NumberStringConverter());
            TableCell<JavaFxModel, Number> tableCell = callback.call(param);

            tableCell.setOnScroll(event -> {
                if(event.isControlDown()) {
                    event.consume();
                    JavaFxModel m = tableCell.getTableRow().getItem();
                    int prio = m.getPriority();
                    if(event.getDeltaY() < 0) {
                        prio--;
                    } else {
                        prio++;
                    }
                    prio = Math.min(Math.max(0, prio), 100);
                    m.setPriority(prio);
                    updatePriority(m, prio);
                }
            });

            return tableCell;
        }
    }
}
