/*! sheetjs (C) SheetJS -- https://sheetjs.com */

/* simple wrapper to evaluate code snippets */
fn eval_code(c: &mut boa_engine::Context, code: &str) -> Result<std::string::String, boa_engine::JsError> {
  let src = boa_engine::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() {
  /* initialize */
  let context = &mut boa_engine::Context::default();

  /* load library */
  match eval_code(context, include_str!("../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 mut iter = std::env::args();
    let path: String = iter.nth(1).expect("must specify a file name");

    let file: Vec<u8> = std::fs::read(path.clone()).unwrap();
  
    /* push data to boa */
    let array: boa_engine::object::builtins::JsArrayBuffer = boa_engine::object::builtins::JsArrayBuffer::from_byte_block(file, context).unwrap();
    let attrs = boa_engine::property::Attribute::WRITABLE | boa_engine::property::Attribute::ENUMERABLE | boa_engine::property::Attribute::CONFIGURABLE;
    let _ = context.register_global_property(boa_engine::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}"); }
  }
}