import { Platform } from "react-native";

import firebase from "../config/firebase";

export function uploadFileToFirebase({ uri, path }) {
  return new Promise(async (resolve, reject) => {
    try {
      let resultResize = { uri };

      const response = await fetch(resultResize.uri);
      const blob = await response.blob();

      const uploadTask = firebase.storage().ref(path).put(blob);

      uploadTask.on(
        Platform.OS === "web"
          ? "state_changed"
          : firebase.storage.TaskEvent.STATE_CHANGED,
        (snapshot) => {
          if (
            Platform.OS !== "web" &&
            snapshot.state === firebase.storage.TaskState.SUCCESS
          ) {
            snapshot.ref.getDownloadURL().then((resultURI) => {
              resolve({ resultURI });
            });
          }
        },
        (error) => {
          reject(error);
        },
        async () => {
          const url = await firebase.storage().ref(path).getDownloadURL();

          resolve({ resultURI: url });
        }
      );
    } catch (e) {
      reject(e);
    }
  });
}
