import { jsx as _jsx } from "react/jsx-runtime";
import { createContext, useContext, useEffect, useState } from "react";
export class DocumentSelection {
    object;
    objects;
    setState;
    /**
     * The collection id to which the selected objects belong to.
     */
    collectionId;
    singleSelection = false;
    constructor(object, collectionId, objects, setState) {
        this.object = object;
        this.objects = objects;
        this.setState = setState;
        this.singleSelection = Object.keys(this.objects).length === 0;
        this.collectionId = collectionId;
    }
    isSingleSelection() {
        return this.singleSelection;
    }
    hasSelection() {
        return this.object !== undefined || this.size() !== 0;
    }
    size() {
        return Object.keys(this.objects).length;
    }
    getObjectIds() {
        return Object.keys(this.objects);
    }
    getObjectId() {
        return this.object?.id;
    }
    clone() {
        return new DocumentSelection(this.object, this.collectionId, this.objects, this.setState);
    }
    add(object) {
        this.objects[object.id] = object;
        this.singleSelection = Object.keys(this.objects).length === 0;
        this.setState(this.clone());
    }
    remove(objectId) {
        delete this.objects[objectId];
        this.singleSelection = Object.keys(this.objects).length === 0;
        this.setState(this.clone());
    }
    addAll(objects) {
        for (const obj of objects) {
            this.objects[obj.id] = obj;
        }
        this.setState(this.clone());
    }
    isSelected(objectId) {
        return this.objects[objectId] !== undefined;
    }
    removeAll() {
        this.objects = {};
        this.singleSelection = true;
        this.setState(this.clone());
    }
}
const DocumentSelectionContext = createContext(undefined);
export function useDocumentSelection() {
    const selection = useContext(DocumentSelectionContext);
    if (!selection) {
        throw new Error("useObjectSelection must be used within a ObjectSelectionProvider");
    }
    return selection;
}
export function useOptionalDocumentSelection() {
    return useContext(DocumentSelectionContext);
}
export function DocumentSelectionProvider({ value, collectionId, children }) {
    const [selection, setSelection] = useState();
    useEffect(() => {
        const selection = new DocumentSelection(value, collectionId, {}, setSelection);
        setSelection(selection);
    }, [value]);
    return selection && (_jsx(DocumentSelectionContext.Provider, { value: selection, children: children }));
}
//# sourceMappingURL=DocumentSelectionProvider.js.map