import download from "downloadjs";
import { Filesystem, Directory } from "@capacitor/filesystem";
import platformUtil from "./platformUtil";
import { alertStore } from "../stores/alertStore";

const downloadUtil = {
  async pngFile(dataUri: string, filename: string) {
    if (platformUtil.isAny(["ios", "android"])) {
      const permission = await Filesystem.requestPermissions();
      if (permission.publicStorage === "granted") {
        await Filesystem.writeFile({
          path: filename,
          data: dataUri,
          directory: Directory.Documents,
        });
        const location = platformUtil.is("ios") ? "files" : "documents";
        alertStore().replace("info", `Saved to ${location}`);
      }
    } else {
      download(dataUri, filename, "image/png");
    }
  },
};

export default downloadUtil;
