import { AppObjectUC } from "@vived/core";
import { StateMachineEntity } from "../../StateMachine";
import { LabelEntity } from "../Entities";
export class SerializeCustomLabels extends AppObjectUC {
    constructor() {
        super(...arguments);
        this.name = "serialize-custom-labels";
    }
}
SerializeCustomLabels.type = "SerializeCustomLabels";
export function makeSerializeCustomLabels(appObject) {
    return new SerializeCustomLabelsImp(appObject);
}
export class SerializeCustomLabelsImp extends SerializeCustomLabels {
    getSystemState() {
        const customLabels = [];
        const allLabels = this.appObjects.getAllComponents(LabelEntity.type);
        allLabels.forEach((label) => {
            if (label.hasCustomLabel)
                customLabels.push({
                    objectId: label.appObject.id,
                    customLabel: label.custom,
                });
        });
        const state = {
            customLabels,
        };
        return state;
    }
    applySystemState(state, version, durationS) {
        if (version === 1) {
            return this.applyStateV1(state, durationS);
        }
        else {
            this.applyDefaultState();
        }
    }
    applyStateV1(state, durationS) {
        const { customLabels } = state;
        if (!customLabels || customLabels.length === 0) {
            this.applyDefaultState();
            return;
        }
        // Create a Map for faster lookups
        const customLabelsLookup = new Map();
        customLabels.forEach((customLabel) => {
            customLabelsLookup.set(customLabel.objectId, customLabel.customLabel);
        });
        const allLabels = this.appObjects.getAllComponents(LabelEntity.type);
        allLabels.forEach((label) => {
            const appObjectId = label.appObject.id;
            label.custom = customLabelsLookup.get(appObjectId) ?? "";
        });
        customLabelsLookup.forEach((customLabel, objectId) => {
            const appObject = this.appObjects.getOrCreate(objectId);
            const label = LabelEntity.addIfMissing(appObject);
            label.custom = customLabel;
        });
    }
    applyDefaultState() {
        const allLabels = this.appObjects.getAllComponents(LabelEntity.type);
        allLabels.forEach((label) => {
            label.custom = "";
        });
    }
    constructor(appObj) {
        super(appObj, SerializeCustomLabels.type);
        this.seriliziationVersion = 1;
        const stateMachine = this.appObjects.getSingleton(StateMachineEntity.type);
        if (stateMachine) {
            stateMachine.registerSerializedSystem(this);
        }
        else {
            this.warn("Unable to find StateMachineEntity");
        }
    }
}
//# sourceMappingURL=SerializeCustomLabels.js.map