import { GLTFLoader } from 'three/examples/jsm/loaders/GLTFLoader';

import * as Types from "../../../types/world/worldTypes";
import { getWallItems } from '../../../services/factoryBuilder/assest/wallAsset/getWallItemsApi';

//////////  Load the Wall Items's intially of there is any  //////////

async function loadInitialWallItems(
    setWallItems: Types.setWallItemSetState,
    AssetConfigurations: Types.AssetConfigurations
): Promise<void> {

    const email = localStorage.getItem('email')
    const organization = (email!.split("@")[1]).split(".")[0];

    const items = await getWallItems(organization);

    localStorage.setItem("WallItems", JSON.stringify(items));
    if (items.length > 0) {
        const storedWallItems: Types.wallItems = items;

        const loadedWallItems = await Promise.all(storedWallItems.map(async (item) => {
            const loader = new GLTFLoader();
            return new Promise<Types.WallItem>((resolve) => {
            loader.load(AssetConfigurations[item.modelname!].modelUrl, (gltf) => {
                const model = gltf.scene;
                model.uuid = item.modeluuid!;

                model.children[0].children.forEach((child: any) => {
                if (child.name !== "CSG_REF") {
                    child.castShadow = true;
                    child.receiveShadow = true;
                }
                });

                resolve({
                type: item.type,
                model: model,
                modelname: item.modelname,
                scale: item.scale,
                csgscale: item.csgscale,
                csgposition: item.csgposition,
                position: item.position,
                quaternion: item.quaternion,
                });
            });
            });
        }));

        setWallItems(loadedWallItems);
    }
}

export default loadInitialWallItems;
