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

export function useStoreHandler() {
    const { materialStore, storageUnitStore, productStore } = useSceneContext();
    const { getMaterialById, removeMaterial, setEndTime } = materialStore();
    const { addCurrentMaterial, updateCurrentLoad } = storageUnitStore();
    const { getModelUuidByActionUuid } = productStore();
    const { selectedProductStore } = useProductContext();
    const { selectedProduct } = selectedProductStore();

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

    const handleStore = useCallback((action: StorageAction, materialId?: string) => {
        if (!action || action.actionType !== 'store' || !materialId) return;

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

        const modelUuid = getModelUuidByActionUuid(selectedProduct.productUuid, action.actionUuid);
        if (!modelUuid) return;

        setEndTime(material.materialId, performance.now());
        removeMaterial(material.materialId);
        addCurrentMaterial(modelUuid, material.materialType, material.materialId);
        updateCurrentLoad(modelUuid, 1);

        storeLogStatus(material.materialName, `performed Store action`);

    }, [getMaterialById]);

    return {
        handleStore,
    };
}