Source: data/retrievetoilets.js

import { getDatabase, ref, child, get } from "firebase/database";
import {
  ref as storeRef,
  uploadString,
  getDownloadURL,
  getStorage,
  uploadBytes,
  deleteObject,
  getMetadata,
} from "firebase/storage";
import { useEffect, useState } from "react";

const database = getDatabase();
const storage = getStorage();

/**
 * The function `getAllToilets` retrieves all toilet data from a Firebase Realtime Database and returns
 * it as an array of objects.
 * @returns The `getAllToilets` function returns an array of toilet objects if toilets are found in the
 * database. If no toilets are found, it logs a message saying "No toilets found in the database" and
 * returns `null`. If there is an error retrieving the toilets from the database, it logs the error and
 * throws it to propagate it to the caller.
 */
export async function getAllToilets() {
  const toiletsRef = ref(database, "toilets");

  try {
    const snapshot = await get(toiletsRef);
    if (snapshot.exists()) {
      const toiletsData = snapshot.val();
      // Convert the object of objects to an array of objects
      const toiletsArray = Object.values(toiletsData);
      return toiletsArray;
    } else {
      console.log("No toilets found in the database.");
      return null;
    }
  } catch (error) {
    console.error("Error retrieving toilets from database:", error);
    throw error; // Propagate the error to the caller
  }
}

/**
 * The `toiletLink` function asynchronously retrieves the download URL for a specific image file stored
 * in Firebase Storage.
 * @returns The `toiletLink` function returns a URL link to download the `toilet_icon.png` image file
 * stored in the `mapicons` folder in the storage.
 */
export const toiletLink = async () => {
  const storageRef = storeRef(storage, `mapicons/toilet_icon.png`);
  const link = await getDownloadURL(storageRef);
  return link;
};