#include <nan.h>

#include "polyfill/unpack.h"

using namespace std;


NAN_METHOD(Wasm) {
  const char* name = args[0]->IsNull() ? nullptr : *NanUtf8String(args[0]);
  v8::Local<v8::Value> inBuffer = args[1];
  const uint8_t* inBytes =
      reinterpret_cast<uint8_t*>(node::Buffer::Data(inBuffer->ToObject()));

  if (!asmjs::has_magic_number(inBytes)) {
    return NanThrowError("Input data is not a packed asm.js file");
  }

  uint32_t unpackedSize = asmjs::unpacked_size(inBytes, name);
  vector<uint8_t> outBytes(unpackedSize);
  asmjs::unpack(inBytes, name, outBytes.size(), outBytes.data());

  v8::Local<v8::Value> outBuffer =
      NanNew(reinterpret_cast<char*>(outBytes.data()), outBytes.size());
  NanReturnValue(outBuffer);
}


void Init (v8::Handle<v8::Object> exports, v8::Handle<v8::Object> module) {
  module->Set(
      NanNew<v8::String>("exports")
    , NanNew<v8::FunctionTemplate>(Wasm)->GetFunction()
  );
}


NODE_MODULE(wasm, Init)
