Files
Mav-Mobile-UI/src/hooks/useCameraOutput.ts

98 lines
2.7 KiB
TypeScript
Raw Normal View History

import { useMutation, useQuery } from "@tanstack/react-query";
import { CAM_BASE } from "../utils/config";
import { useEffect } from "react";
import { toast } from "sonner";
import type { BearerTypeFieldType, OptionalBOF2Constants } from "../types/types";
const getDispatcherConfig = async () => {
const response = await fetch(`${CAM_BASE}/api/fetch-config?id=Dispatcher`);
if (!response.ok) throw new Error("Cannot get dispatcher configuration");
return response.json();
};
const updateDispatcherConfig = async (data: BearerTypeFieldType) => {
const updateConfigPayload = {
id: "Dispatcher",
fields: [
{
property: "propEnabled",
value: data.enabled,
},
{
property: "propFormat",
value: data.format,
},
],
};
const response = await fetch(`${CAM_BASE}/api/update-config?id=Dispatcher`, {
method: "POST",
body: JSON.stringify(updateConfigPayload),
});
if (!response.ok) throw new Error("Cannot update dispatcher configuration");
return response.json();
};
const updateBackOfficeDispatcher = async (data: OptionalBOF2Constants) => {
console.log(data);
const bof2ContantsPayload = {
id: "Dispatcher-bof2-constants",
fields: [
{
property: "propFeedIdentifier",
value: data?.FFID,
},
{
property: "propSourceIdentifier",
value: data?.SCID,
},
{
property: "propTimeZoneType",
value: data?.timestampSource,
},
{
property: "propGpsFormat",
value: data?.GPSFormat,
},
],
};
const response = await fetch(`${CAM_BASE}/api/update-config?id=Dispatcher-bof2-constants`, {
method: "POST",
body: JSON.stringify(bof2ContantsPayload),
});
if (!response.ok) throw new Error("Cannot update dispatcher configuration");
return response.json();
};
export const useCameraOutput = () => {
const dispatcherQuery = useQuery({
queryKey: ["dispatcher"],
queryFn: getDispatcherConfig,
});
const dispatcherMutation = useMutation({
mutationFn: updateDispatcherConfig,
mutationKey: ["dispatcherUpdate"],
onError: (error) => toast.error(error.message),
onSuccess: (data) => {
if (data) {
toast.success("Settings successfully updated");
}
},
});
const backOfficeDispatcherMutation = useMutation({
mutationKey: ["backofficedDispatcher"],
mutationFn: updateBackOfficeDispatcher,
});
useEffect(() => {
if (dispatcherQuery.isError) toast.error(dispatcherQuery.error.message);
}, [dispatcherQuery?.error?.message, dispatcherQuery.isError]);
return {
dispatcherQuery,
dispatcherMutation,
backOfficeDispatcherMutation,
};
};