import { Loading, scaleUtils } from '@widergy/mobile-ui'; import React, { Fragment, useCallback, useEffect, useMemo, useState } from 'react'; import { View } from 'react-native'; import { useBluetoothContext } from '../../../../bluetooth/useBluetoothContext'; import { BluetoothState } from '../../../../bluetooth/constants'; import Colors from '../../../Colors'; import GeneralStep from '../../../GeneralStep'; import ProbeReadingToRead from '../../../assets/probeReading/probeReadingToRead.png'; import MeterFamilyTypeBadge from '../MeterFamilyTypeBadge'; import styles from './styles'; import { resetToZero } from '../../../../bluetooth/reset/resetToZero'; import { COMMUNICATION_INTERVAL_PER_PROBE_IN_MS } from '../../../../bluetooth/constants'; const InteractionWithProbe = ({ children, onClose, loadingCurrentDevice, meterFamilyType, mockCode, onSuccess, readingTimeouts, readStrategy, timeoutRef, translations, showFamilyBadgeLibrary, }) => { const SIZE_LOADING = scaleUtils.moderateHorizontalScale(164); const [beginResetting, setBeginResetting] = useState(false); const bluetoothContext = useBluetoothContext(); const onBeginResetting = useCallback(() => { if (readingTimeouts?.probeReadingTimeoutInMilliseconds) { clearTimeout(timeoutRef.current); timeoutRef.current = setTimeout(() => { onClose({ message: translations.timeoutError }); }, readingTimeouts?.probeReadingTimeoutInMilliseconds); } setBeginResetting(true); }, [onClose, readingTimeouts?.probeReadingTimeoutInMilliseconds, timeoutRef, translations.timeoutError]); const disabledStep = !bluetoothContext.isConnected() || bluetoothContext.batteryPercentage == null; const resetError = useMemo( () => (translations?.resetError ? { message: translations?.resetError } : undefined), [translations?.resetError], ); useEffect(() => { let subscription: { unsubscribe: any }; if (!disabledStep) { setTimeout(() => { subscription = resetToZero({ bluetoothContext, mockCode, onBeginResetting, onClose, onSuccess, readStrategy, resetError, }); }, COMMUNICATION_INTERVAL_PER_PROBE_IN_MS); } return () => { subscription?.unsubscribe?.(); }; // eslint-disable-next-line react-hooks/exhaustive-deps }, [disabledStep]); useEffect(() => { if ( bluetoothContext.connectionError || (bluetoothContext.bluetoothState === BluetoothState.IDLE && !loadingCurrentDevice && !bluetoothContext.targetDevice) ) onClose(); }, [ bluetoothContext.bluetoothState, bluetoothContext.connectionError, loadingCurrentDevice, bluetoothContext.targetDevice, onClose, ]); return ( {!beginResetting ? ( { onClose(); }, key: 'exit', secondary: true, disabled: disabledStep, }, ]} withOpacity={disabledStep} > {children && children} {showFamilyBadgeLibrary && ( )} ) : ( { onClose(); }, key: 'exit', secondary: true, }, ]} > {children && children} {showFamilyBadgeLibrary && ( )} )} ); }; export default InteractionWithProbe;