import React, { useEffect, useRef, useState } from 'react'
import { useMachineStore } from '../../../../../store/simulation/useMachineStore';
import { usePlayButtonStore } from '../../../../../store/usePlayButtonStore';
import MachineAnimator from '../animator/machineAnimator';

function MachineInstance({ machineDetail }: any) {
    const [currentPhase, setCurrentPhase] = useState<string>('idle');
    let isIncrememtable = useRef<boolean>(true);
    const { isPlaying } = usePlayButtonStore();
    const { machines, addCurrentAction, setMachineState, setMachineActive } = useMachineStore();

    const reset = () => {
        setCurrentPhase("idle");
        setMachineState(machineDetail.modelUuid, 'idle');
        setMachineActive(machineDetail.modelUuid, false);
        isIncrememtable.current = true;
    }
    const increment = () => {
        if (isIncrememtable.current) {
            addCurrentAction(machineDetail.modelUuid, "machine-action-2468-1357-8024")
            isIncrememtable.current = false;
        }
    }
    function machineStatus(modelId: string, status: string) {
        // console.log(`${modelId} , ${status}`);

    }

    useEffect(() => {
        if (isPlaying) {
            if (!machineDetail.isActive && machineDetail.state === "idle" && currentPhase == "idle" && !machineDetail.currentAction) {
                setTimeout(() => {
                    increment();
                }, 5000);
                machineStatus(machineDetail.modelUuid, 'Machine is idle and waiting for next instruction.')
            } else if (!machineDetail.isActive && machineDetail.state === "idle" && currentPhase == "idle" && machineDetail.currentAction) {
                setCurrentPhase("processing");
                setMachineState(machineDetail.modelUuid, 'running');
                setMachineActive(machineDetail.modelUuid, true);
                machineStatus(machineDetail.modelUuid, "Machine started processing")
            }
        }
    }, [currentPhase, isPlaying, machines])

    function handleCallBack() {
        if (currentPhase == "processing") {
            setMachineState(machineDetail.modelUuid, 'idle');
            setMachineActive(machineDetail.modelUuid, false);
            setCurrentPhase("idle")
            isIncrememtable.current = true;
            machineStatus(machineDetail.modelUuid, "Machine has completed the processing")
        }
    }
    // console.log('currentPhase: ', currentPhase);



    return (
        <>
            <MachineAnimator processingTime={machineDetail.point.action.processTime} handleCallBack={handleCallBack} currentPhase={currentPhase} machineUuid={machineDetail.modelUuid} machineStatus={machineStatus} reset={reset} />

        </>
    )
}

export default MachineInstance