import { GLTFLoader } from 'three/examples/jsm/loaders/GLTFLoader';
import { toast } from 'react-toastify';

import * as THREE from 'three';
import * as Types from "../../../../types/world/worldTypes";
import * as CONSTANTS from '../../../../types/world/worldConstants';
// import { setWallItem } from '../../../../services/factoryBuilder/assest/wallAsset/setWallItemApi';
import { Socket } from 'socket.io-client';

async function AddWallItems(
    selected: Types.String,
    raycaster: THREE.Raycaster,
    CSGGroup: Types.RefMesh,
    AssetConfigurations: Types.AssetConfigurations,
    setWallItems: Types.setWallItemSetState,
    socket: Socket<any>
): Promise<void> {

    //////////  Load Wall GLtf's and set the positions, rotation, type etc. in state and store in localstorage  ////////// 

    let intersects = raycaster?.intersectObject(CSGGroup.current!, true);
    const wallRaycastIntersection = intersects?.find((child) => child.object.name.includes("WallRaycastReference"));

    if (wallRaycastIntersection) {
        const intersectionPoint = wallRaycastIntersection;
        const loader = new GLTFLoader();
        loader.load(AssetConfigurations[selected].modelUrl, async (gltf) => {
            const model = gltf.scene;
            model.userData = { wall: intersectionPoint.object.parent };
            model.children[0].children.forEach((child) => {
                if (child.name !== "CSG_REF") {
                    child.castShadow = true;
                    child.receiveShadow = true;
                }
            });

            const config = AssetConfigurations[selected];
            let positionY = typeof config.positionY === 'function' ? config.positionY(intersectionPoint) : config.positionY;
            if (positionY === 0) {
                positionY = Math.floor(intersectionPoint.point.y / CONSTANTS.wallConfig.height) * CONSTANTS.wallConfig.height;
            }

            const newWallItem = {
                type: config.type,
                model: model,
                modelname: selected,
                scale: config.scale,
                csgscale: config.csgscale,
                csgposition: config.csgposition,
                position: [intersectionPoint.point.x, positionY, intersectionPoint.point.z] as [number, number, number],
                quaternion: intersectionPoint.object.quaternion.clone() as Types.QuaternionType
            };

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

            //REST

            // await setWallItem(
            //     organization,
            //     model.uuid,
            //     newWallItem.modelname,
            //     newWallItem.type!,
            //     newWallItem.csgposition!,
            //     newWallItem.csgscale!,
            //     newWallItem.position,
            //     newWallItem.quaternion,
            //     newWallItem.scale!,
            // )

            //SOCKET

            const data = {
                organization: organization,
                modeluuid: model.uuid,
                modelname: newWallItem.modelname,
                type: newWallItem.type!,
                csgposition: newWallItem.csgposition!,
                csgscale: newWallItem.csgscale!,
                position: newWallItem.position,
                quaternion: newWallItem.quaternion,
                scale: newWallItem.scale!,
                socketId: socket.id
            }

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

            setWallItems((prevItems) => {
                const updatedItems = [...prevItems, newWallItem];

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

                localStorage.setItem("WallItems", JSON.stringify(WallItemsForStorage));
                toast.success("Model Added!");

                return updatedItems;
            });
        });
    }
}

export default AddWallItems;
