import { toast } from 'react-toastify';

import * as Types from "../../../../types/world/worldTypes";
// import { deleteWallItem } from '../../../../services/factoryBuilder/assest/wallAsset/deleteWallItemApi';
import { Socket } from 'socket.io-client';

function DeleteWallItems(
    hoveredDeletableWallItem: Types.RefMesh,
    setWallItems: Types.setWallItemSetState,
    wallItems: Types.wallItems,
    socket: Socket<any>
): void {

    ////////// Deleting the hovered Wall GLTF from thewallItems and also update it in the localstorage //////////

    if (hoveredDeletableWallItem.current && hoveredDeletableWallItem.current.parent) {
        setWallItems([]);
        let WallItemsRef = wallItems;
        const removedItem = WallItemsRef.find((item) => item.model?.uuid === hoveredDeletableWallItem.current?.parent?.uuid);
        const Items = WallItemsRef.filter((item) => item.model?.uuid !== hoveredDeletableWallItem.current?.parent?.uuid);

        setTimeout(async () => {
            WallItemsRef = Items;
            setWallItems(WallItemsRef);

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

            //REST

            // await deleteWallItem(organization, removedItem?.model?.uuid!, removedItem?.modelname!)

            //SOCKET

            const data = {
                organization: organization,
                modeluuid: removedItem?.model?.uuid!,
                modelname: removedItem?.modelname!,
                socketId: socket.id
            }

            socket.emit('v1:wallItems:delete', data);

            const WallItemsForStorage = WallItemsRef.map(item => {
                const { model, ...rest } = item;
                return {
                    ...rest,
                    modeluuid: model?.uuid,
                };
            });

            localStorage.setItem("WallItems", JSON.stringify(WallItemsForStorage));
            toast.success("Model Removed!");
            hoveredDeletableWallItem.current = null;
        }, 50);
    }
}

export default DeleteWallItems;
