"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const fs = require("fs-extra");
const base_command_1 = require("./base-command");
const utils_1 = require("@joplin/utils");
const uuid_1 = require("@joplin/lib/uuid");
const app_1 = require("./app");
const locale_1 = require("@joplin/lib/locale");
const Note_1 = require("@joplin/lib/models/Note");
const Setting_1 = require("@joplin/lib/models/Setting");
const BaseModel_1 = require("@joplin/lib/BaseModel");
class Command extends base_command_1.default {
    usage() {
        return 'edit <note>';
    }
    description() {
        return (0, locale_1._)('Edit note.');
    }
    // eslint-disable-next-line @typescript-eslint/no-explicit-any -- Old code before rule was applied
    async action(args) {
        let tempFilePath = null;
        const onFinishedEditing = async () => {
            if (tempFilePath)
                fs.removeSync(tempFilePath);
        };
        const textEditorPath = () => {
            if (Setting_1.default.value('editor'))
                return Setting_1.default.value('editor');
            if (process.env.EDITOR)
                return process.env.EDITOR;
            throw new Error((0, locale_1._)('No text editor is defined. Please set it using `config editor <editor-path>`'));
        };
        try {
            // -------------------------------------------------------------------------
            // Load note or create it if it doesn't exist
            // -------------------------------------------------------------------------
            const title = args['note'];
            if (!(0, app_1.default)().currentFolder())
                throw new Error((0, locale_1._)('No active notebook.'));
            let note = await (0, app_1.default)().loadItem(BaseModel_1.ModelType.Note, title);
            this.encryptionCheck(note);
            if (!note) {
                const ok = await this.prompt((0, locale_1._)('Note does not exist: "%s". Create it?', title));
                if (!ok)
                    return;
                note = await Note_1.default.save({ title: title, parent_id: (0, app_1.default)().currentFolder().id });
                note = await Note_1.default.load(note.id);
            }
            // -------------------------------------------------------------------------
            // Create the file to be edited and prepare the editor program arguments
            // -------------------------------------------------------------------------
            let editorPath = textEditorPath();
            let editorArgs = (0, utils_1.splitCommandString)(editorPath);
            editorPath = editorArgs[0];
            editorArgs = editorArgs.splice(1);
            const originalContent = await Note_1.default.serializeForEdit(note);
            tempFilePath = `${Setting_1.default.value('tempDir')}/${uuid_1.default.create()}.md`;
            editorArgs.push(tempFilePath);
            await fs.writeFile(tempFilePath, originalContent);
            // -------------------------------------------------------------------------
            // Start editing the file
            // -------------------------------------------------------------------------
            this.logger().info('Disabling fullscreen...');
            (0, app_1.default)().gui().showModalOverlay((0, locale_1._)('Starting to edit note. Close the editor to get back to the prompt.'));
            await (0, app_1.default)().gui().forceRender();
            const termState = (0, app_1.default)().gui().termSaveState();
            const spawnSync = require('child_process').spawnSync;
            const result = spawnSync(editorPath, editorArgs, { stdio: 'inherit' });
            if (result.error)
                this.stdout((0, locale_1._)('Error opening note in editor: %s', result.error.message));
            (0, app_1.default)().gui().termRestoreState(termState);
            (0, app_1.default)().gui().hideModalOverlay();
            (0, app_1.default)().gui().forceRender();
            // -------------------------------------------------------------------------
            // Save the note and clean up
            // -------------------------------------------------------------------------
            const updatedContent = await fs.readFile(tempFilePath, 'utf8');
            if (updatedContent !== originalContent) {
                const updatedNote = await Note_1.default.unserializeForEdit(updatedContent);
                updatedNote.id = note.id;
                await Note_1.default.save(updatedNote);
                this.stdout((0, locale_1._)('Note has been saved.'));
            }
            this.dispatch({
                type: 'NOTE_SELECT',
                id: note.id,
            });
            await onFinishedEditing();
        }
        catch (error) {
            await onFinishedEditing();
            throw error;
        }
    }
}
module.exports = Command;
//# sourceMappingURL=command-edit.js.map