import React, { useEffect } from 'react'
import * as SimulationTypes from '../../../types/simulationTypes';
import { useSimulationStates } from '../../../store/store';
import StaticMachineInstances from './staticMachineInstances';

interface ArmBotState {
    uuid: string;
    position: [number, number, number];
    rotation: [number, number, number];
    status: string;
    material: string;
    triggerId: string;
    actions: { uuid: string; name: string; speed: number; processes: { triggerId: string; startPoint: string; endPoint: string }[]; };
}

interface StaticMachineState {
    uuid: string;
    status: string;
    actions: { uuid: string; name: string; buffer: number; material: string; };
    machineTriggerId: string;
    connectedArmBot: string;
}

type StaticMachineProps = {
    setArmBots: React.Dispatch<React.SetStateAction<ArmBotState[]>>;
    staticMachines: StaticMachineState[];
    setStaticMachines: React.Dispatch<React.SetStateAction<StaticMachineState[]>>;
}

function StaticMachine({ setArmBots, staticMachines, setStaticMachines }: StaticMachineProps) {

    const { simulationStates } = useSimulationStates();

    useEffect(() => {
        const filtered = simulationStates.filter((s): s is SimulationTypes.StaticMachineEventsSchema => s.type === "StaticMachine");
        const initialStates: StaticMachineState[] = filtered
            .filter(machine => machine.points.connections.targets.length > 0)
            .map(machine => ({
                uuid: machine.modeluuid,
                status: "idle",
                actions: machine.points.actions,
                machineTriggerId: machine.points.triggers.uuid,
                connectedArmBot: machine.points.connections.targets[0].modelUUID
            }));
        setStaticMachines(initialStates);
    }, [simulationStates]);

    const updateArmBotTriggerAndMachineStatus = (armBotUuid: string, triggerId: string, machineId: string) => {
        setArmBots((prevArmBots) => {
            return prevArmBots.map(bot => {
                if (bot.uuid === armBotUuid) {
                    return { ...bot, triggerId: triggerId };
                }
                return bot;
            });
        });
        setStaticMachines((prevStaticMachines) => {
            return prevStaticMachines.map(machine => {
                if (machine.uuid === machineId) {
                    return { ...machine, status: "idle" };
                } else {
                    return machine;
                }
            });
        });
    }

    return (
        <>
            {staticMachines.map((machine, index) => (
                <StaticMachineInstances key={index} machine={machine} updateArmBotTriggerAndMachineStatus={updateArmBotTriggerAndMachineStatus} />
            ))}
        </>
    )
}

export default StaticMachine;