import { useCallback } from "react";
import { useSceneContext } from "../../../../scene/sceneContext";

export function useProcessHandler() {
    const { materialStore, machineStore, productStore } = useSceneContext();
    const { getMaterialById, setMaterial } = materialStore();
    const { addCurrentAction } = machineStore();
    const { getModelUuidByActionUuid, selectedProduct } = productStore();

    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.productUuid, 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,
    };
}
