import * as React from 'react'; import { Alert, AlertDescription, AlertIcon, AlertTitle, Box, Button, Flex, FormControl, FormErrorMessage, FormLabel, Textarea, useToast, } from '@chakra-ui/react'; import { ClipboardText } from '@phosphor-icons/react'; import { useTranslation } from 'react-i18next'; import { SaveButton } from '../../Buttons/SaveButton'; import { Modal } from '../Modal'; import { FileInputButton } from 'components/Buttons/FileInputButton'; import { useConfigureDevice } from 'hooks/Network/Commands'; import { useGetDevice } from 'hooks/Network/Devices'; import { AxiosError } from 'models/Axios'; export type ConfigureModalProps = { serialNumber: string; modalProps: { isOpen: boolean; onClose: () => void; }; }; const _ConfigureModal = ({ serialNumber, modalProps }: ConfigureModalProps) => { const { t } = useTranslation(); const toast = useToast(); const configure = useConfigureDevice({ serialNumber }); const getDevice = useGetDevice({ serialNumber }); const [newConfig, setNewConfig] = React.useState(''); const onChange = React.useCallback((e: React.ChangeEvent) => { setNewConfig(e.target.value); }, []); const onImportConfiguration = () => { setNewConfig(getDevice.data?.configuration ? JSON.stringify(getDevice.data.configuration, null, 4) : ''); }; const isValid = React.useMemo(() => { try { JSON.parse(newConfig); return true; } catch (error) { return false; } }, [newConfig]); const onSave = () => { try { const config = JSON.parse(newConfig); configure.mutate(config, { onSuccess: (data) => { if (data.errorCode === 0) { toast({ id: `configure-success-${serialNumber}`, title: t('common.success'), description: data.status === 'pending' ? 'Command is pending! It will execute once the device connects' : t('controller.configure.success'), status: 'success', duration: 5000, isClosable: true, position: 'top-right', }); modalProps.onClose(); } else if (data.errorCode === 1) { toast({ id: `configure-warning-${serialNumber}`, title: 'Warning', description: `${data?.errorText ?? 'Unknown Warning'}`, status: 'warning', duration: 5000, isClosable: true, position: 'top-right', }); modalProps.onClose(); } else { toast({ id: `config-error-${serialNumber}`, title: t('common.error'), description: `${data?.errorText ?? 'Unknown Error'} (Code ${data.errorCode})`, status: 'error', duration: 5000, isClosable: true, position: 'top-right', }); } modalProps.onClose(); }, }); } catch (e) { // do nothing } }; React.useEffect(() => { if (modalProps.isOpen) { getDevice.refetch(); } else { setNewConfig(''); } }, [modalProps.isOpen]); return ( } > <> {configure.error && ( {t('common.error')} {(configure.error as AxiosError)?.response?.data?.ErrorDescription} )} {t('controller.configure.warning')} 0}> {t('configurations.one')} setNewConfig(v)} refreshId="1" accept=".json" isStringFile />