/* run code, get result as a Rust String */
fn eval_code(scope: &mut v8::HandleScope, code: &str) -> std::string::String {
  let source = v8::String::new(scope, &code).unwrap();
  let script = v8::Script::compile(scope, source, None).unwrap();
  let result = script.run(scope).unwrap();
  return result.to_string(scope).unwrap().to_rust_string_lossy(scope);
}


fn main() {
  create_snapshot();
}

fn create_snapshot() {
  /* initialize */
  let platform = v8::new_default_platform(0, false).make_shared();
  v8::V8::initialize_platform(platform);
  v8::V8::initialize();

  let startup_data = {
    let mut isolate = v8::Isolate::snapshot_creator(None);
    {
      let handle_scope = &mut v8::HandleScope::new(&mut isolate);
      let context = v8::Context::new(handle_scope);
      let context_scope = &mut v8::ContextScope::new(handle_scope, context);

      /* load library */
      {
        let script = std::fs::read_to_string("./xlsx.full.min.js").expect("Error reading xlsx.full.min.js");
        let _result = eval_code(context_scope, &script);
      }
      context_scope.set_default_context(context);
    }
    isolate.create_blob(v8::FunctionCodeHandling::Clear).unwrap()
  };
  let blob: Vec<u8> = startup_data.to_vec();
  std::fs::write("snapshot.bin", blob).unwrap();
}
