import * as FileSystem from "expo-file-system";
import { useGalery } from "./useGalery";
import { useState } from "react";
import { ApiRequestStatus } from "../const/api_request_states";
import { set } from "react-hook-form";
import * as ExpoCrypto from "expo-crypto";

const TRAVEL_ALBUM = "Magic Towns Travel";

export const useDownloadFile = () => {
  const { saveToGalery } = useGalery();
  const [requestStatus, setRequestStatus] = useState(ApiRequestStatus.IDLE);
  const setLoading = async () => setRequestStatus(ApiRequestStatus.LOADING);
  const handleDownload = async (url: string) => {
    try {
      await setLoading();
      const { uri } = await FileSystem.downloadAsync(
        url,
        FileSystem.documentDirectory + `${ExpoCrypto.randomUUID()}.jpg`
      );
      await saveToGalery(uri, TRAVEL_ALBUM);
      setRequestStatus(ApiRequestStatus.SUCCESS);
    } catch (error) {
      setRequestStatus(ApiRequestStatus.ERROR);
    }
  };

  return { handleDownload, saveFileStatus: requestStatus };
};
