import { base64 } from "rfc4648";

export function readFile(file: File): Promise<string> {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.onload = (event) => resolve(<string>event.target.result); // desired file content
    reader.onerror = (error) => reject(error);
    reader.readAsText(file); // you could also read images and other binaries
  });
}

export function searchRecoveryKeyFromFile(file: File): Promise<Uint8Array> {
  return readFile(file).then((content) => {
    let allLine = content.split("\n");
    for (let i = 0; i < allLine.length; i++) {
      let line = allLine[i].trim();
      if (line[0] == "#" && line.length > 0) continue;
      try {
        let result = base64.parse(line);
        if (result.length > 0) {
          return result;
        }
      } catch (e) {
        // just search more
      }
    }
    throw "Can not find recovery key";
  });
}

// it is possible this won't work in some safari browser
export function selectLocalFile(
  allowMultipleSelection: boolean = false
): Promise<FileList> {
  return new Promise((resolve, reject) => {
    let dialog = document.createElement("input");
    dialog.type = "file";
    dialog.style.display = "none";
    dialog.multiple = allowMultipleSelection;
    // on some safari sometimes the file input does not trigger
    // the event after the file-browser selection, if it is not attached to the dom
    // https://stackoverflow.com/questions/47664777/javascript-file-input-onchange-not-working-ios-safari-only
    document.body.appendChild(dialog);
    dialog.addEventListener("change", (e) => {
      let files = dialog.files;
      resolve(files);
      document.body.removeChild(dialog);
    });

    dialog.click();
  });
}

export function getFileFromClipboard(dataTransfer: DataTransfer): File[] {
  
  let result: File[] = [];

  if (dataTransfer.items) {
    for (let i = 0; i < dataTransfer.items.length; i++) {
      let item = dataTransfer.items[i];
      var file = item.getAsFile ? item.getAsFile() : null;
      //console.log("item: " + item.kind + " (" + item.type + ")");

      // if you use clipboard, the name is always the same
      // if you want to paste multiple file, it is recommended to generate unique names
      if (file?.name.startsWith("image.")){
        try {
          // make unique name by time and index
          // otherwise it will be "image" or something like that for all item
          let newName = "" + new Date().getTime() + "_" + i + "_" + file.name;
          file = new File([file], newName, { type: file.type });
        } catch (e) {
          // ok, then keep your name
        }
      }
      

      if (/^image\//.test(item.type) && file) {
        //console.log("img", file);
        result.push(file);
      } else if (file) {
        //console.log("binary", file);
        result.push(file);
      } else if (item.kind === "string") {
        item.getAsString(function (text) {
          //console.log("text", text);
        });
      }
    }
  }

  return result;
}
