/* global alert */ import React, { useEffect, useState } from 'react'; import { Image, View, TouchableOpacity, Platform } from 'react-native'; import { RNCamera } from 'react-native-camera'; import { Icon } from 'react-native-elements'; import ImagePicker from 'react-native-image-picker'; import PropTypes from 'prop-types'; import { useNavigationParam, useNavigation } from 'react-navigation-hooks'; import DocumentPicker from 'react-native-document-picker'; import RNFS from 'react-native-fs'; const LocalQRCode = require('@remobile/react-native-qrcode-local-image'); const ScanQRCode = ({ onBarScanned = useNavigationParam('onBarScanned'), cameraPreviewIsPaused = false, showCloseButton = true, showFileImportButton = useNavigationParam('showFileImportButton') || false, launchedBy = useNavigationParam('launchedBy'), }) => { const [isLoading, setIsLoading] = useState(false); const { navigate } = useNavigation(); const onBarCodeRead = ret => { if (!isLoading && !cameraPreviewIsPaused) { setIsLoading(true); try { if (showCloseButton && launchedBy) { navigate(launchedBy); } if (ret.additionalProperties) { onBarScanned(ret.data, ret.additionalProperties); } else { onBarScanned(ret.data); } } catch (e) { console.log(e); } } setIsLoading(false); }; const showFilePicker = async () => { setIsLoading(true); try { const res = await DocumentPicker.pick(); const file = await RNFS.readFile(res.uri); const fileParsed = JSON.parse(file); if (fileParsed.keystore.xpub) { onBarCodeRead({ data: fileParsed.keystore.xpub, additionalProperties: { masterFingerprint: fileParsed.keystore.ckcc_xfp } }); } else { throw new Error(); } } catch (err) { if (!DocumentPicker.isCancel(err)) { alert('The selected file does not contain a wallet that can be imported.'); } setIsLoading(false); } setIsLoading(false); }; useEffect(() => {}, [cameraPreviewIsPaused]); return ( {!cameraPreviewIsPaused && !isLoading && ( )} {showCloseButton && ( navigate(launchedBy)} > )} { if (!isLoading) { setIsLoading(true); ImagePicker.launchImageLibrary( { title: null, mediaType: 'photo', takePhotoButtonTitle: null, }, response => { if (response.uri) { const uri = Platform.OS === 'ios' ? response.uri.toString().replace('file://', '') : response.path.toString(); LocalQRCode.decode(uri, (error, result) => { if (!error) { onBarCodeRead({ data: result }); } else { alert('The selected image does not contain a QR Code.'); } }); } setIsLoading(false); }, ); } }} > {showFileImportButton && ( )} ); }; ScanQRCode.navigationOptions = { header: null, }; ScanQRCode.propTypes = { launchedBy: PropTypes.string, onBarScanned: PropTypes.func, cameraPreviewIsPaused: PropTypes.bool, showFileImportButton: PropTypes.bool, showCloseButton: PropTypes.bool, }; export default ScanQRCode;