/*! sheetjs (C) SheetJS -- https://sheetjs.com */
/* run code and ignore result */
fn eval_code(scope: &mut v8::HandleScope, code: &str) {
  let source = v8::String::new(scope, code).unwrap();
  let script = v8::Script::compile(scope, source, None).unwrap();
  let _ = script.run(scope);
}

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

  /* use SnapshotCreator */
  let mut isolate = v8::Isolate::snapshot_creator(None, Default::default());

  /* scope enforces the lifetime of the `&mut isolate` in `handle_scope` */
  {
    /* same steps as normal flow */
    let handle_scope = &mut v8::HandleScope::new(&mut isolate);
    let context = v8::Context::new(handle_scope, Default::default());
    let context_scope = &mut v8::ContextScope::new(handle_scope, context);

    /* instructs the snapshot creator to dump the new context */
    context_scope.set_default_context(context);

    /* load scripts */
    let scripts = vec!["./xlsx.full.min.js", "./xlsx.zahl.js"];
    for path in &scripts {
      let script = std::fs::read_to_string(path).unwrap_or_else(|_| panic!("Error reading {}", path));
      eval_code(context_scope, &script);
    }
  };

  /* create snapshot */
  let startup_data = isolate.create_blob(v8::FunctionCodeHandling::Clear).unwrap();

  /* write to snapshot.bin */
  let blob: Vec<u8> = startup_data.to_vec();
  std::fs::write("snapshot.bin", blob).unwrap();
}