/*! sheetjs (C) SheetJS -- https://sheetjs.com */
use std::path::Path;
use std::string::String;
use std::fs;

use boa_engine::{js_string, Context, Source, JsError};
use boa_engine::object::builtins::JsArrayBuffer;
use boa_engine::property::Attribute;

fn eval_file(c: &mut Context, path: &str) -> Result<String, JsError> {
  let src = Source::from_filepath(Path::new(path)).unwrap();
  match c.eval(src) {
    Ok(res) => { return Ok(res.to_string(c).unwrap().to_std_string_escaped()); }
    Err(e) => { return Err(e); }
  };
}

fn eval_code(c: &mut Context, code: &str) -> Result<String, JsError> {
  let src = Source::from_bytes(code);
  match c.eval(src) {
    Ok(res) => { return Ok(res.to_string(c).unwrap().to_std_string_escaped()); }
    Err(e) => { return Err(e); }
  };
}

fn main() {
  let context = &mut Context::default();

  /* load library */
  match eval_file(context, "./xlsx.full.min.js") {
    Ok(_res) => {}
    Err(e) => { return eprintln!("Uncaught {e}"); }
  }

  /* get version string */
  match eval_code(context, "XLSX.version") {
    Ok(res) => { println!( "SheetJS library version {}", res); }
    Err(e) => { return eprintln!("Uncaught {e}"); }
  }

  /* read file */
  let data: Vec<u8> = fs::read("pres.xlsx").unwrap();
  let array: JsArrayBuffer = JsArrayBuffer::from_byte_block(data, context).unwrap();
  let attrs = Attribute::WRITABLE | Attribute::ENUMERABLE | Attribute::CONFIGURABLE;
  context.register_global_property(js_string!("buf"), array, attrs);

  /* parse workbook and assign to global `wb` property */
  match eval_code(context, "void (globalThis.wb = XLSX.read(buf))") {
    Ok(_res) => { }
    Err(e) => { return eprintln!("Uncaught {e}"); }
  }

  /* print CSV of first worksheet */
  match eval_code(context, "XLSX.utils.sheet_to_csv(wb.Sheets[wb.SheetNames[0]])") {
    Ok(res) => { println!( "{}", res); }
    Err(e) => { return eprintln!("Uncaught {e}"); }
  }
}