import Model from "../../Data/Model.js";
import GlobalStorage from "./GlobalStorage.js";
import GroupStorage from "./GroupStorage.js";
import { GroupStorageCollection } from "./GroupStorageCollection.js";
const STORAGE_KEY = "__storage__";
export default class StorageManager extends Model {
    constructor(options) {
        super(options);
        this.m_parent = options.parent;
        this.state.unset("parent");
        this.deserialize();
    }
    get parent() {
        return this.m_parent;
    }
    get global() {
        return this.m_global;
    }
    get groups() {
        return this.m_groups;
    }
    get storageData() {
        return this.parent.attributes
            .get(STORAGE_KEY);
    }
    set storageData(value) {
        this.parent.attributes
            .set(STORAGE_KEY, value);
    }
    toJSON() {
        return {
            global: this.global.toJSON(),
            groups: this.groups.toJSON()
        };
    }
    serialize() {
        this.storageData = JSON.stringify(this.toJSON());
    }
    deserialize() {
        let data = null;
        if (this.storageData != null) {
            try {
                data = JSON.parse(this.storageData);
            }
            catch (ex) {
                data = this.storageData;
            }
        }
        this.m_global = new GlobalStorage(_.extend({
            parent: this.parent
        }, data?.global || {}));
        let groups = new GroupStorageCollection();
        this.parent.data.featureSet.groups.forEach(group => {
            groups.add(new GroupStorage({
                parent: this.parent,
                id: group.id
            }));
        });
        if (data?.groups) {
            data.groups.forEach(data => {
                let group = groups.get(data.id);
                if (group != null) {
                    group.state.set(data);
                }
            });
        }
        this.m_groups = groups;
    }
}
