import * as FileSystem from 'expo-file-system';
import { StorageAccessFramework } from 'expo-file-system';
import * as Sharing from 'expo-sharing';
import { Platform } from 'react-native';

import { showFeedback } from '../feedback/showFeedback';

export const downloadFileAsync = async (base64Data: string, fileName: string, format: string) => {
  try {
    const tmp = fileName.split('.');
    const name = `${tmp[0]}.${tmp[1].toLocaleLowerCase()}`;

    const uri = FileSystem.cacheDirectory + name;
    await FileSystem.writeAsStringAsync(uri, base64Data, {
      encoding: FileSystem.EncodingType.Base64,
    });

    const shareOptions = {
      mimeType: `application/${format}`,
      UTI: `public.${format}`,
      filename: name,
    };

    if (Platform.OS === 'ios') {
      await Sharing.shareAsync(uri, shareOptions);
    } else {
      const permissions = await StorageAccessFramework.requestDirectoryPermissionsAsync();
      if (!permissions.granted) {
        return;
      }
      try {
        await StorageAccessFramework.createFileAsync(
          permissions.directoryUri,
          name,
          `application/${format}`,
        ).then(async uri => {
          await FileSystem.writeAsStringAsync(uri, base64Data, {
            encoding: FileSystem.EncodingType.Base64,
          });
        });
      } catch (err) {
        showFeedback({
          title: 'Při ukládání souboru došlo k chybě.',
          type: 'danger',
          err,
        });
      }
    }

    showFeedback({
      title: 'Soubor byl úspěšně uložen.',
      type: 'success',
    });
  } catch (err) {
    showFeedback({
      title: 'Při ukládání souboru došlo k chybě.',
      type: 'danger',
      err,
    });
  }
};
