<script>
import { Filesystem, Directory, Encoding } from '@capacitor/filesystem';
import { onMount } from 'svelte';
import { read, utils, version, writeXLSX } from 'xlsx';

let html = "";
let tbl;

/* Fetch and update the state once */
onMount(async() => {
  const f = await (await fetch("https://docs.sheetjs.com/pres.xlsx")).arrayBuffer();
  const wb = read(f); // parse the array buffer
  const ws = wb.Sheets[wb.SheetNames[0]]; // get the first worksheet
  html = utils.sheet_to_html(ws); // generate HTML and update state
});

/* get state data and export to XLSX */
async function exportFile() {
  const elt = tbl.getElementsByTagName("TABLE")[0];
  const wb = utils.table_to_book(elt);

  /* export to XLSX encoded in a Base64 string  */
  const data = writeXLSX(wb, { type: "base64" });

  /* `writeFile` cannot overwrite, so try to delete file first */
  try {
    await Filesystem.deleteFile({
      path: "SheetJSCap.xlsx",
      directory: Directory.Documents
    });
  } catch(e) { /* ignore error */ }

  /* attempt to write to the device */
  await Filesystem.writeFile({
    path: "SheetJSCap.xlsx",
    data,
    directory: Directory.Documents
  });
  alert(`Exported to ${Directory.Documents}/SheetJSCap.xlsx`);
}

/* show file picker, read file, load table */
async function importFile(evt) {
  const f = evt.target.files[0];
  const wb = read(await f.arrayBuffer());
  const ws = wb.Sheets[wb.SheetNames[0]]; // get the first worksheet
  html = utils.sheet_to_html(ws); // generate HTML and update state
}
</script>

<main>
  <h3>SheetJS × CapacitorJS { version }</h3>
  <input type="file" on:change={importFile}/>
  <button on:click={exportFile}>Export XLSX</button>
  <div bind:this={tbl}>{@html html}</div>
</main>
