import { useEffect } from "react";
import { useFrame } from "@react-three/fiber";
import { useSceneContext } from "../../../../scene/sceneContext";

// import { findConveyorSubsequence } from '../../../simulator/functions/getConveyorSequencesInProduct';

function ConveyorInstance({ conveyor }: { readonly conveyor: ConveyorStatus }) {
    const { materialStore, conveyorStore, productStore } = useSceneContext();
    const { getProductById, selectedProduct } = productStore();
    const { getMaterialsByCurrentModelUuid } = materialStore();
    const { setConveyorPaused } = conveyorStore();

    useFrame(() => {
        const product = getProductById(selectedProduct.productUuid);
        if (!product) return;

        const conveyorMaterials = getMaterialsByCurrentModelUuid(conveyor.modelUuid);
        if (conveyorMaterials && conveyorMaterials.length > 0) {
            const hasPausedMaterials = conveyorMaterials.some((material) => material.isPaused);

            if (hasPausedMaterials) {
                setConveyorPaused(conveyor.modelUuid, true);
            } else {
                setConveyorPaused(conveyor.modelUuid, false);
            }
        } else {
            setConveyorPaused(conveyor.modelUuid, false);
        }

        // const conveyorSubsequence = findConveyorSubsequence(product, conveyor.modelUuid);

        // if (!conveyorSubsequence || !conveyorSubsequence.currentSubSequence) {
        //     setConveyorPaused(conveyor.modelUuid, false);
        //     return;
        // }

        // const { currentSubSequence } = conveyorSubsequence;

        // const allMaterials = currentSubSequence.flatMap(event =>
        //     getMaterialsByCurrentModelUuid(event.modelUuid)
        // );

        // const hasPausedMaterials = allMaterials.some(mat => mat?.isPaused);

        // currentSubSequence.forEach(event => {
        //     if (event.type === 'transfer') {
        //         setConveyorPaused(event.modelUuid, hasPausedMaterials);
        //     }
        // });
    });

    useEffect(() => {
        // console.log('conveyor: ', conveyor);
    }, [conveyor]);

    return <></>;
}

export default ConveyorInstance;
