package ctbrec.ui.action;

import java.io.File;
import java.time.Instant;

import ctbrec.Config;
import ctbrec.GlobalThreadPool;
import ctbrec.Model;
import ctbrec.Settings.DirectoryStructure;
import ctbrec.ui.DesktopIntegration;
import ctbrec.ui.controls.Dialogs;
import javafx.scene.Cursor;
import javafx.scene.Node;

public class OpenRecordingsDir {

    private Model selectedModel;
    private Node source;

    public OpenRecordingsDir(Node source, Model selectedModel) {
        this.source = source;
        this.selectedModel = selectedModel;
    }

    public void execute() {
        source.setCursor(Cursor.WAIT);
        File fileForRecording = Config.getInstance().getFileForRecording(selectedModel, ".mp4", Instant.now());
        final File dir = getModelDirectory(fileForRecording);
        if (dir.exists()) {
            GlobalThreadPool.submit(() -> DesktopIntegration.open(dir));
        } else {
            Dialogs.showError(source.getScene(), "Directory does not exist", "There are no recordings for this model", null);
        }
        source.setCursor(Cursor.DEFAULT);
    }

    private File getModelDirectory(File fileForRecording) {
        File dir = fileForRecording.getParentFile();
        if (Config.getInstance().getSettings().recordingsDirStructure == DirectoryStructure.ONE_PER_RECORDING) {
            dir = dir.getParentFile();
        }
        return dir;
    }
}
