"use strict";
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.NotebookSerializer = void 0;
const detectIndent = require("detect-indent");
const vscode = require("vscode");
const constants_1 = require("./constants");
const deserializers_1 = require("./deserializers");
const serializers_1 = require("./serializers");
const fnv = require("@enonic/fnv-plus");
class NotebookSerializer {
    constructor(context) {
        this.context = context;
    }
    async deserializeNotebook(content, _token) {
        let contents = '';
        try {
            contents = new TextDecoder().decode(content);
        }
        catch {
        }
        let json = contents ? JSON.parse(contents) : {};
        if (json.__webview_backup) {
            const backupId = json.__webview_backup;
            const uri = this.context.globalStorageUri;
            const folder = uri.with({ path: this.context.globalStorageUri.path.replace('vscode.ipynb', 'ms-toolsai.jupyter') });
            const fileHash = fnv.fast1a32hex(backupId);
            const fileName = `${fileHash}.ipynb`;
            const file = vscode.Uri.joinPath(folder, fileName);
            const data = await vscode.workspace.fs.readFile(file);
            json = data ? JSON.parse(data.toString()) : {};
            if (json.contents && typeof json.contents === 'string') {
                contents = json.contents;
                json = JSON.parse(contents);
            }
        }
        // Then compute indent from the contents (only use first 1K characters as a perf optimization)
        const indentAmount = contents ? detectIndent(contents.substring(0, 1000)).indent : ' ';
        const preferredCellLanguage = (0, deserializers_1.getPreferredLanguage)(json.metadata);
        // Ensure we always have a blank cell.
        if ((json.cells || []).length === 0) {
            json.cells = [
                {
                    cell_type: 'code',
                    execution_count: null,
                    metadata: {},
                    outputs: [],
                    source: ''
                }
            ];
        }
        // For notebooks without metadata default the language in metadata to the preferred language.
        if (!json.metadata || (!json.metadata.kernelspec && !json.metadata.language_info)) {
            json.metadata = json.metadata || { orig_nbformat: constants_1.defaultNotebookFormat.major };
            json.metadata.language_info = json.metadata.language_info || { name: preferredCellLanguage };
        }
        const data = (0, deserializers_1.jupyterNotebookModelToNotebookData)(json, preferredCellLanguage);
        data.metadata = data.metadata || {};
        data.metadata.indentAmount = indentAmount;
        return data;
    }
    serializeNotebook(data, _token) {
        return new TextEncoder().encode(this.serializeNotebookToString(data));
    }
    serializeNotebookToString(data) {
        const notebookContent = data.metadata?.custom || {};
        notebookContent.cells = notebookContent.cells || [];
        notebookContent.nbformat = notebookContent.nbformat || 4;
        notebookContent.nbformat_minor = notebookContent.nbformat_minor || 2;
        notebookContent.metadata = notebookContent.metadata || { orig_nbformat: 4 };
        notebookContent.cells = data.cells
            .map(cell => (0, serializers_1.createJupyterCellFromNotebookCell)(cell))
            .map(serializers_1.pruneCell);
        const indentAmount = data.metadata && 'indentAmount' in data.metadata && typeof data.metadata.indentAmount === 'string' ?
            data.metadata.indentAmount :
            ' ';
        return JSON.stringify(notebookContent, undefined, indentAmount);
    }
}
exports.NotebookSerializer = NotebookSerializer;
//# sourceMappingURL=notebookSerializer.js.map