/*
 * Copyright (C) 2016-2020 Kano Computing Ltd.
 * License: http://www.gnu.org/licenses/gpl-2.0.txt GNU General Public License v2
 */
/* eslint class-methods-use-this: "off" */
import { Plugin } from '../editor/plugin.js';
import { debounce } from '../util/debounce.js';
export class StoragePlugin extends Plugin {
    constructor(key, debounceDelay = 3000) {
        super();
        this.enabled = true;
        this.debounceDelay = debounceDelay;
        this.key = key;
        this._debouncedSave = debounce(() => {
            this.save();
        }, debounceDelay);
    }
    disable() {
        this.enabled = false;
    }
    enable() {
        this.enabled = false;
    }
    onInstall(editor) {
        this.editor = editor;
        this.editor.sourceEditor.onDidCodeChange(() => {
            this._debouncedSave();
        });
        this.editor.onDidReset(() => {
            this.save();
        });
    }
    load() {
        this.read(this.getKey())
            .then((app) => {
            if (!this.editor || !app) {
                return;
            }
            this.editor.load(app);
        });
    }
    save() {
        if (!this.enabled || !this.editor) {
            return;
        }
        const savedApp = this.editor.export();
        this.write(this.getKey(), savedApp);
    }
    getKey() {
        let value = 'storage';
        if (typeof this.key === 'function') {
            value = this.key();
        }
        else {
            value = this.key;
        }
        return value;
    }
}
export default StoragePlugin;
//# sourceMappingURL=storage.js.map