import { BaseBlockTransformer, Workspace } from '@blockeditor/store';
const SURFACE_TEXT_UNIQ_IDENTIFIER = 'affine:surface:text';
// Used for group children field
const SURFACE_YMAP_UNIQ_IDENTIFIER = 'affine:surface:ymap';
export class SurfaceBlockTransformer extends BaseBlockTransformer {
    _toJSON(value) {
        if (value instanceof Workspace.Y.Text) {
            return {
                [SURFACE_TEXT_UNIQ_IDENTIFIER]: true,
                delta: value.toDelta(),
            };
        }
        else if (value instanceof Workspace.Y.Map) {
            return {
                [SURFACE_YMAP_UNIQ_IDENTIFIER]: true,
                json: value.toJSON(),
            };
        }
        return value;
    }
    _fromJSON(value) {
        if (value instanceof Object) {
            if (Reflect.has(value, SURFACE_TEXT_UNIQ_IDENTIFIER)) {
                const yText = new Workspace.Y.Text();
                yText.applyDelta(Reflect.get(value, 'delta'));
                return yText;
            }
            else if (Reflect.has(value, SURFACE_YMAP_UNIQ_IDENTIFIER)) {
                const yMap = new Workspace.Y.Map();
                const json = Reflect.get(value, 'json');
                Object.entries(json).forEach(([key, value]) => {
                    yMap.set(key, value);
                });
                return yMap;
            }
        }
        return value;
    }
    _elementToJSON(element) {
        const value = {};
        element.forEach((_value, _key) => {
            value[_key] = this._toJSON(_value);
        });
        return value;
    }
    elementFromJSON(element) {
        const yMap = new Workspace.Y.Map();
        Object.entries(element).forEach(([key, value]) => {
            yMap.set(key, this._fromJSON(value));
        });
        return yMap;
    }
    async toSnapshot(payload) {
        const snapshot = await super.toSnapshot(payload);
        const elementsValue = payload.model.elements.getValue();
        const value = {};
        if (elementsValue) {
            elementsValue.forEach((element, key) => {
                value[key] = this._elementToJSON(element);
            });
        }
        snapshot.props = {
            elements: value,
        };
        return snapshot;
    }
    async fromSnapshot(payload) {
        const snapshotRet = await super.fromSnapshot(payload);
        const elementsJSON = snapshotRet.props.elements;
        const yMap = new Workspace.Y.Map();
        Object.entries(elementsJSON).forEach(([key, value]) => {
            const element = this.elementFromJSON(value);
            yMap.set(key, element);
        });
        const elements = this._internal.Boxed(yMap);
        snapshotRet.props = {
            elements,
        };
        return snapshotRet;
    }
}
//# sourceMappingURL=surface-transformer.js.map