"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const ste_events_1 = require("ste-events");
const StorageUtilities_1 = require("../storage/StorageUtilities");
class DataFormFile {
    constructor() {
        this._isLoaded = false;
        this._onLoaded = new ste_events_1.EventDispatcher();
    }
    get isLoaded() {
        return this._isLoaded;
    }
    get file() {
        return this._file;
    }
    set file(newFile) {
        this._file = newFile;
    }
    get onLoaded() {
        return this._onLoaded.asEvent();
    }
    get title() {
        if (this.formDefinition) {
            return this.formDefinition.title;
        }
        return this._title;
    }
    get id() {
        return this._id;
    }
    set id(newId) {
        this._id = newId;
        if (newId) {
            const underscore = newId.lastIndexOf("_");
            if (underscore >= 0 && underscore < newId.length - 2) {
                this._title = newId.substring(0, underscore);
            }
            else {
                this._title = newId;
            }
        }
    }
    static async ensureOnFile(file, loadHandler) {
        let dff;
        if (file.manager === undefined) {
            dff = new DataFormFile();
            dff.file = file;
            file.manager = dff;
        }
        if (file.manager !== undefined && file.manager instanceof DataFormFile) {
            dff = file.manager;
            if (!dff.isLoaded && loadHandler) {
                dff.onLoaded.subscribe(loadHandler);
            }
            await dff.load();
        }
        return dff;
    }
    persist() {
        if (this._file === undefined) {
            return;
        }
        const fdString = JSON.stringify(this.formDefinition, null, 2);
        this._file.setContent(fdString);
    }
    async load() {
        if (this._file === undefined || this._isLoaded) {
            return;
        }
        await this._file.loadContent();
        if (this._file.content === null || this._file.content instanceof Uint8Array) {
            return;
        }
        this.formDefinition = StorageUtilities_1.default.getJsonObject(this._file);
        this._isLoaded = true;
    }
}
exports.default = DataFormFile;

//# sourceMappingURL=../maps/dataform/DataFormFile.js.map
