export const uploadFile = (file: File, type: "dataUrl" | "text" = "text") => {
  return new Promise<string>((resolve, reject) => {
    const reader = new FileReader();
    reader.addEventListener("load", () => {
      if (reader.error) {
        return reject(reader.error);
      }
      if (reader.result == null) {
        return reject(new Error("Result was empty"));
      }
      resolve(reader.result.toString());
    });

    if (type === "dataUrl") {
      reader.readAsDataURL(file);
    }
    if (type === "text") {
      reader.readAsText(file);
    }
  });
};

export const saveFile = (name: string, type: string, content: string) => {
  const a = document.createElement("a");
  const blob = new Blob([content], {
    type,
  });
  const url = URL.createObjectURL(blob);
  a.setAttribute("href", url);
  a.setAttribute("download", name);
  a.click();
};

export const selectLocalFiles = (type: string[]) => {
  return new Promise<FileList>((resolve, reject) => {
    const fileInput = document.createElement("input");
    fileInput.type = "file";
    fileInput.accept = type.join(",");
    fileInput.oninput = (evt) => {
      const files: FileList | undefined = (evt.currentTarget as any).files;
      if (!files) {
        return resolve(new FileList());
      }

      resolve(files);
    };
    fileInput.click();
  });
};
