import * as THREE from 'three';
import { GLTFLoader } from 'three/examples/jsm/loaders/GLTFLoader';
import { DRACOLoader } from 'three/examples/jsm/loaders/DRACOLoader';
import { retrieveGLTF, storeGLTF } from '../../../utils/indexDB/idbUtils';

const loader = new GLTFLoader();
const dracoLoader = new DRACOLoader();
dracoLoader.setDecoderPath('https://cdn.jsdelivr.net/npm/three@0.160.0/examples/jsm/libs/draco/gltf/');
loader.setDRACOLoader(dracoLoader);
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.modelfileID === item.modelfileID)
    );

    for (const item of uniqueItems) {
        const modelID = item.modelfileID;
        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' })
};
