import * as React from 'react';
import { useCallback, useState } from 'react';
import { useToast } from '@chakra-ui/react';
import { MainComponent } from '../MainComponent/MainComponent';
import { get } from '../../../services/HttpService';
export const MonitorComponent = () => {
const [fetchedFile, setFetchedFile] = useState<any[] | null>(null);
const [initialized, setInitialized] = useState<boolean>(false);
const url = 'api/subscription-update';
const additionalRequestParams = { user_name: 'string', email: 'string' };
const toast = useToast();
const displayToast = (title: string) => {
toast({
title,
status: 'success',
duration: 3000,
isClosable: true,
});
};
const getMonitoringData = useCallback((subscriptionId?: string) => {
if (!initialized) {
setInitialized(true);
displayToast('Monitoring started');
}
if (subscriptionId) {
get(`api/latest-updates/${subscriptionId}`).then((res) => {
if (
fetchedFile?.length !== res.data.results.length ||
res.data['any_updates']
) {
setFetchedFile(res.data.results);
const date = new Date();
// Didn't want to add external library (e.g. date-fns) just for this
const hour = date.getHours();
const minutes = date.getMinutes();
const seconds = date.getSeconds();
const currentTime = `${hour < 10 ? `0${hour}` : hour}:${
minutes < 10 ? `0${minutes}` : minutes
}:${seconds < 10 ? `0${seconds}` : seconds}`;
displayToast(`Data has been updated at ${currentTime}`);
}
});
}
}, []);
const sideEffect = (response: any) => {
getMonitoringData(response?.subscribtion_id);
setInterval(() => getMonitoringData(response?.subscription_id), 10000);
};
return (
<MainComponent
url={url}
isMonitoringService
additionalRequestParams={additionalRequestParams}
sideEffectData={fetchedFile}
onFileUploadEffect={(res) =>
!initialized ? sideEffect(res) : null
}
/>
);
};