import { retrieveGLTF, storeGLTF } from '../../../utils/indexDB/idbUtils';

let url_Backend_dwinzo = `http://${process.env.REACT_APP_SERVER_MARKETPLACE_URL}`;

onmessage = async (event) => {
    const { floorItems } = event.data;

    const uniqueItems = floorItems.filter((item, index, self) =>
        index === self.findIndex((t) => t.assetId === item.assetId)
    );

    for (const item of uniqueItems) {
        if (item.assetId === null || item.assetId === undefined) {
            continue;
        }
        const modelID = item.assetId;
        const indexedDBModel = await retrieveGLTF(modelID);

        let modelBlob;
        if (indexedDBModel) {
            modelBlob = indexedDBModel;
            const message = "gltfLoaded";
            postMessage({ message, modelID, modelBlob });
        } else {
            const modelUrl = `${url_Backend_dwinzo}/api/v2/AssetFile/${modelID}`;
            const modelBlob = await fetch(modelUrl).then((res) => res.blob());
            await storeGLTF(modelID, modelBlob);
            const message = "gltfLoaded";
            postMessage({ message, modelID, modelBlob });
        }
    }

    postMessage({ message: 'done' });
};
