export default function FileUpload()

in src/FileUpload.tsx [63:258]


export default function FileUpload() {
  const {colors} = useTheme();
  const [client] = useIoTCentralClient();
  const [simulated] = useSimulation();
  const {screen} = useScreenDimensions();
  const {append} = useContext(LogsContext);
  const [uploading, setUploading] = useBoolean(false);
  const [showSelector, setShowSelector] = useBoolean(false);
  const [uploadStatus, setuploadStatus] = useState<boolean | undefined>(
    undefined,
  );

  const [fileName, setFileName] = useState('');
  const [fileSize, setFileSize] = useState('');

  const styles = useMemo<Literal<ViewStyle | TextStyle>>(
    () => ({
      flex1: {flex: 1},
      container: {
        flex: 0,
        marginBottom: 40,
        alignItems: 'center',
        marginHorizontal: 40,
      },
      simulatedContainer: {
        flex: 1,
        justifyContent: 'center',
        alignItems: 'center',
        marginHorizontal: 30,
      },
      centerText: {
        textAlign: 'center',
      },
      listItem: {
        backgroundColor: colors.card,
      },
      listItemText: {
        color: colors.text,
      },
      closeItemText: {
        color: 'gray',
      },
      card: {
        flex: 0,
        height: screen.height / 2,
        width: screen.width - 100,
      },
      cardWrapper: {flex: 2, alignItems: 'center', justifyContent: 'center'},
    }),
    [colors, screen],
  );

  useEffect(() => {
    setuploadStatus(undefined);
  }, [uploading]);

  const startUpload = useCallback(
    (fn: (options: ImageLibraryOptions, callback: Callback) => void) => {
      fn(
        {
          mediaType: 'photo',
          includeBase64: true, //TODO: remove and use uri
        },
        async response => {
          setShowSelector.False();
          if (response.didCancel) {
            console.log('User cancelled');
          } else if (response.errorMessage) {
            console.log('ImagePicker Error: ', response.errorMessage);
          } else {
            // send response data

            const rawFileType = response.assets?.[0].type;
            let fileType = 'image/jpeg';

            // There is a bug with the image picker (at least on iOS) that causes the type for .jpg images to come back as 'image/jpg'
            // which is invalid and will cause any mime type parsing to misidentify the file type
            // Bug: https://github.com/react-native-image-picker/react-native-image-picker/issues/1856
            if (rawFileType && rawFileType !== 'image/jpg') {
              fileType = rawFileType;
            }

            let curfileName = response.assets?.[0].fileName;
            if (!curfileName && Platform.OS === 'ios') {
              curfileName = response.assets?.[0].uri?.split('/').pop();
            }
            try {
              append({
                eventName: 'FILE UPLOAD',
                eventData: `Starting upload of file ${curfileName}`,
              });
              setFileName(curfileName!);
              setFileSize(formatBytes(response.assets?.[0].fileSize!));
              setUploading.True();
              // await new Promise(r => setTimeout(r, 6000));
              const res = await client?.uploadFile(
                curfileName as string,
                fileType,
                response.assets?.[0].base64,
                'base64',
              );
              if (res && res.status >= 200 && res.status < 300) {
                append({
                  eventName: 'FILE UPLOAD',
                  eventData: `Successfully uploaded ${curfileName}`,
                });
                setuploadStatus(true);
              } else {
                append({
                  eventName: 'FILE UPLOAD',
                  eventData: `Error uploading ${curfileName}${
                    res?.errorMessage ? `. Reason:${res?.errorMessage}` : '.'
                  }`,
                });
                setuploadStatus(false);
              }
            } catch (e) {
              console.log(e);
            }
          }
        },
      );
    },
    [setShowSelector, setUploading, append, client],
  );

  if (simulated) {
    return (
      <View style={styles.simulatedContainer}>
        <Headline style={styles.centerText}>
          {Strings.Simulation.Enabled}
        </Headline>
        <Text style={styles.centerText}>
          {' '}
          {Strings.FileUpload.NotAvailable} {Strings.Simulation.Disable}
        </Text>
      </View>
    );
  }

  return (
    <View style={styles.flex1}>
      <View style={styles.cardWrapper}>
        <Card
          containerStyle={styles.card}
          enabled={false}
          title=""
          onPress={setShowSelector.True}
          value={getCardValue({
            uploading,
            fileSize,
            fileName,
            uploadStatus,
            setUploading,
          })}
        />
      </View>

      <View style={styles.container}>
        <Text>
          {Strings.FileUpload.Footer}
          <Link
            onPress={() => Linking.openURL(Strings.FileUpload.LearnMore.Url)}>
            {Strings.FileUpload.LearnMore.Title}
          </Link>
        </Text>
      </View>
      <BottomPopup
        isVisible={showSelector}
        onDismiss={() => setShowSelector.False()}>
        <ListItem
          onPress={() => {
            startUpload(launchImageLibrary);
          }}
          containerStyle={styles.listItem}>
          <ListItem.Content>
            <ListItem.Title style={styles.listItemText}>
              {Strings.FileUpload.Modes.Library}
            </ListItem.Title>
          </ListItem.Content>
        </ListItem>
        <ListItem
          onPress={() => {
            startUpload(launchCamera);
          }}
          containerStyle={styles.listItem}>
          <ListItem.Content>
            <ListItem.Title style={styles.listItemText}>
              {Strings.FileUpload.Modes.Camera}
            </ListItem.Title>
          </ListItem.Content>
        </ListItem>
      </BottomPopup>
    </View>
  );
}