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

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

    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
    };
}