import { useCallback } from "react";
import { useMaterialStore } from "../../../../../store/simulation/useMaterialStore";
import { useMachineStore } from "../../../../../store/simulation/useMachineStore";
import { useProductStore } from "../../../../../store/simulation/useProductStore";
import { useSelectedProduct } from "../../../../../store/simulation/useSimulationStore";

export function useProcessHandler() {
    const { getMaterialById, setMaterial } = useMaterialStore();
    const { addCurrentAction } = useMachineStore();
    const { getModelUuidByActionUuid } = useProductStore();
    const { selectedProduct } = useSelectedProduct();

    const processLogStatus = (materialUuid: string, status: string) => {
        echo.log(`${materialUuid}, ${status}`);
    }

    const handleProcess = useCallback((action: MachineAction, materialId?: string) => {
        if (!action || action.actionType !== 'process' || !materialId) return;

        const { swapMaterial: newMaterialType } = action;

        const material = getMaterialById(materialId);
        if (!material) return;

        const modelUuid = getModelUuidByActionUuid(selectedProduct.productId, action.actionUuid);

        if (!modelUuid) return;
        setMaterial(material.materialId, newMaterialType);

        addCurrentAction(modelUuid, action.actionUuid, newMaterialType, material.materialId);

        processLogStatus(material.materialName, `Swapped to ${newMaterialType}`);
        processLogStatus(material.materialName, `starts Process action`);

    }, [getMaterialById]);

    return {
        handleProcess
    };
}