import { Platform } from "react-native";
import Compressor from "react-native-compressor";
import firebase from "../config/firebase";

export function uploadFileToFirebase({
  uri,
  path,
  shouldCompress = false,
  fileType = "",
}) {
  return new Promise(async (resolve, reject) => {
    try {
      let workingURI = uri;

      // Optionally compress before upload
      try {
        if (shouldCompress && Platform.OS !== "web") {
          if (fileType === "VIDEO") {
            console.log("Compressing video...");
            workingURI = await Compressor.Video.compress(workingURI);
          } else if (fileType === "IMAGE") {
            // Basic image compression
            workingURI = await Compressor.Image.compress(workingURI, {
              compressionMethod: "auto",
            });
          }
        }
      } catch (e) {
        console.warn("Compression failed, uploading original file", e?.message);
        workingURI = uri;
      }

      const response = await fetch(workingURI);
      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);
    }
  });
}
