import { useEffect, useState } from 'kaioken'
import { read, write, utils, version, WorkBook } from 'xlsx';
import { DialogFilter, message, open, save } from '@tauri-apps/api/dialog';
import { fetch, ResponseType } from '@tauri-apps/api/http';
import { readBinaryFile, writeBinaryFile } from '@tauri-apps/api/fs';

const filters: DialogFilter[] = [
  {name: "Excel Binary Workbook", extensions: ["xlsb"]},
  {name: "Excel Workbook", extensions: ["xlsx"]},
  {name: "Excel 97-2004 Workbook", extensions: ["xls"]},
  {name: "Excel 2003 XML Spreadsheet", extensions: ["xml"]},
  {name: "Symbolic Link", extensions: ["slk"]},
  {name: "Flat OpenDocument Spreadsheet", extensions: ["fods"]},
  {name: "OpenDocument Spreadsheet", extensions: ["fods"]},
  // ...
];

export default function SheetJSTauriKaioken() {
  const [data, setData] = useState<any[][]>([[]])
  const [origin, setOrigin] = useState("");

  const update = (wb: WorkBook) => {
    const ws = wb.Sheets[wb.SheetNames[0]];
    const d = utils.sheet_to_json<any[]>(ws, { header: 1})
    setData(d);
  };

  /* Load from File */
  const openFile = async() => {
    try {
      const selected = await open({
        title: "Open Spreadsheet",
        multiple: false,
        directory: false,
        filters
      }) as string;
      const d = await readBinaryFile(selected);
      const wb = read(d);
      update(wb);
      setOrigin(selected);
    } catch(e) { await message((e as Error).message || (e as string), { title: "Load Error", type: "error"}); }
  };

  /* Save to File */
  const saveFile = async() => {
    try {
      const selected = await save({
        title: "Save to Spreadsheet",
        filters
      });
      if(!selected) throw new Error("No file selected");
      const ws = utils.aoa_to_sheet(data);
      const wb = utils.book_new();
      utils.book_append_sheet(wb, ws, "SheetJSTauri");
      const d = write(wb, {type: "buffer", bookType: selected.slice(selected.lastIndexOf(".") + 1) as any}) as Uint8Array;
      await writeBinaryFile(selected, d);
      await message(`File saved to ${selected}`);
    } catch(e) { await message((e as Error).message || (e as string), { title: "Save Error", type: "error"}); }
  };

  /* Download from https://docs.sheetjs.com/pres.numbers */
  useEffect(() => {(async() => {
    try {
      setOrigin("https://docs.sheetjs.com/pres.numbers");
      const response = await fetch<Uint8Array>("https://docs.sheetjs.com/pres.numbers", { method: "GET", responseType: ResponseType.Binary });
      const wb = read(new Uint8Array(response.data));
      update(wb);
    } catch(e) { await message((e as Error).message || (e as string), { title: "Fetch Error", type: "error"}); }
  })(); }, []);

  return (  <div>
    <h1><a href="https://sheetjs.com" target="_blank">
      <img src="https://sheetjs.com/sketch128.png" className="logo" alt="SheetJS" />
    SheetJS × Tauri {version}</a></h1>

    <div className="centre"><button type="button" onclick={openFile}>Load Data</button> or
    <button type="button" onclick={saveFile}>Save Data</button></div>
    <p className="centre"><b className="centre">Data from { origin }</b></p>
    <table className="center"><tbody>
    {data.map((row) => <tr>
      {row.map((cell) => <td>{cell}</td>)}
    </tr>)}
    </tbody></table>
  </div>
  );
}