2025-09-12 08:21:52 +01:00
|
|
|
import { useMutation, useQuery } from "@tanstack/react-query";
|
2025-09-12 13:28:14 +01:00
|
|
|
import { toast } from "sonner";
|
2025-09-29 13:00:56 +01:00
|
|
|
import { CAM_BASE } from "../utils/config";
|
2025-09-12 08:21:52 +01:00
|
|
|
|
2025-09-29 13:00:56 +01:00
|
|
|
const base_url = `${CAM_BASE}/api`;
|
2025-09-12 08:21:52 +01:00
|
|
|
|
2025-09-12 13:28:14 +01:00
|
|
|
const fetchCameraSideConfig = async ({ queryKey }: { queryKey: string[] }) => {
|
2025-09-12 08:21:52 +01:00
|
|
|
const [, cameraSide] = queryKey;
|
|
|
|
|
const fetchUrl = `${base_url}/fetch-config?id=${cameraSide}`;
|
2025-10-06 14:21:56 +01:00
|
|
|
const response = await fetch(fetchUrl, {
|
2025-11-05 16:30:27 +00:00
|
|
|
signal: AbortSignal.timeout(300000),
|
2025-10-06 14:21:56 +01:00
|
|
|
});
|
2025-09-12 08:21:52 +01:00
|
|
|
if (!response.ok) throw new Error("cannot react cameraSide ");
|
|
|
|
|
return response.json();
|
|
|
|
|
};
|
|
|
|
|
|
2025-10-15 11:00:52 +01:00
|
|
|
const updateCamerasideConfig = async (data: { id: string | number; friendlyName: string; cameraAddress: string }) => {
|
2025-09-12 08:21:52 +01:00
|
|
|
const updateUrl = `${base_url}/update-config?id=${data.id}`;
|
|
|
|
|
|
|
|
|
|
const updateConfigPayload = {
|
2025-09-30 11:11:46 +01:00
|
|
|
id: data.friendlyName,
|
2025-09-12 08:21:52 +01:00
|
|
|
fields: [
|
|
|
|
|
{
|
2025-10-13 13:04:09 +01:00
|
|
|
property: "propURI",
|
|
|
|
|
value: data.cameraAddress,
|
2025-09-12 08:21:52 +01:00
|
|
|
},
|
|
|
|
|
],
|
|
|
|
|
};
|
2025-10-15 11:00:52 +01:00
|
|
|
|
2025-09-12 08:21:52 +01:00
|
|
|
const response = await fetch(updateUrl, {
|
|
|
|
|
method: "POST",
|
|
|
|
|
body: JSON.stringify(updateConfigPayload),
|
|
|
|
|
});
|
2025-11-10 13:44:29 +00:00
|
|
|
if (!response.ok) throw new Error("Please make sure fields are filled in correctly");
|
2025-09-12 08:21:52 +01:00
|
|
|
};
|
|
|
|
|
|
|
|
|
|
export const useFetchCameraConfig = (cameraSide: string) => {
|
|
|
|
|
const fetchedConfigQuery = useQuery({
|
|
|
|
|
queryKey: ["cameraSideConfig", cameraSide],
|
|
|
|
|
queryFn: fetchCameraSideConfig,
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
const updateConfigMutation = useMutation({
|
|
|
|
|
mutationKey: ["cameraSideConfigUpdate"],
|
|
|
|
|
mutationFn: updateCamerasideConfig,
|
2025-09-12 13:28:14 +01:00
|
|
|
onError: (error) => toast.error(error.message),
|
|
|
|
|
onSuccess: () => toast("Settings Successfully saved"),
|
2025-09-12 08:21:52 +01:00
|
|
|
});
|
|
|
|
|
|
|
|
|
|
return {
|
|
|
|
|
data: fetchedConfigQuery.data,
|
|
|
|
|
isPending: fetchedConfigQuery.isPending,
|
|
|
|
|
isError: fetchedConfigQuery.isError,
|
|
|
|
|
updateCameraConfig: updateConfigMutation.mutate,
|
2025-09-12 13:28:14 +01:00
|
|
|
updateCameraConfigError: updateConfigMutation.error,
|
2025-10-06 14:21:56 +01:00
|
|
|
updateCameraConfigLoading: updateConfigMutation.isPending,
|
2025-09-12 08:21:52 +01:00
|
|
|
};
|
|
|
|
|
};
|