import firebase from '@firebase/app';
import '@firebase/storage';
export const uploadFile = ({ data, folder, maxSize, userId, downloadUrl = true }) => {
  return new Promise(async (resolve, reject) => {
    try {
      if (!userId || userId === '' || userId === undefined) {
        reject('Not logged in.');
        return;
      }
      if (!data || !data.name) {
        reject('File not valid.');
        return;
      }
      if (data.size > maxSize) {
        reject(`File is too big (max. ${maxSize / 1048576} Mb)`);
        return;
      }
      const ref = firebase.storage().ref(`${userId}/assets/${folder}/${data.name}`);
      // Firebase issue: updating a File/Blob which has been saved previously in IDB does not work.
      const buffer = await new Response(data).arrayBuffer();
      await ref.put(buffer);
      resolve({
        downloadUrl: downloadUrl ? await ref.getDownloadURL() : undefined,
        fullPath: ref.fullPath,
        name: ref.name
      });
    }
    catch (err) {
      reject(err.message());
    }
  });
};
export const getFiles = ({ next, maxResults, folder, userId }) => {
  return new Promise(async (resolve, reject) => {
    try {
      if (!userId || userId === '' || userId === undefined) {
        reject('Not logged in.');
        return;
      }
      const ref = firebase.storage().ref(`${userId}/assets/${folder}`);
      let options = {
        maxResults: maxResults
      };
      if (next) {
        options.pageToken = next;
      }
      const results = await ref.list(options);
      resolve(toStorageFilesList(results));
    }
    catch (err) {
      reject(err);
    }
  });
};
export const deleteFile = async ({ fullPath }) => {
  const ref = firebase.storage().ref(fullPath);
  return ref.delete();
};
const toStorageFilesList = (results) => {
  return new Promise(async (resolve) => {
    if (!results || !results.items || results.items.length <= 0) {
      resolve({
        items: [],
        nextPageToken: null
      });
      return;
    }
    const storageFiles = results.items.map(toStorageFile);
    const items = await Promise.all(storageFiles);
    resolve({
      items: items,
      nextPageToken: results.nextPageToken
    });
  });
};
const toStorageFile = (ref) => {
  return new Promise(async (resolve) => {
    resolve({
      downloadUrl: await ref.getDownloadURL(),
      fullPath: ref.fullPath,
      name: ref.name
    });
  });
};
