// Copyright (c) The NodeRT Contributors
// All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the ""License""); you may
// not use this file except in compliance with the License. You may obtain a
// copy of the License at http://www.apache.org/licenses/LICENSE-2.0
//
// THIS CODE IS PROVIDED ON AN  *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS
// OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY
// IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
// MERCHANTABLITY OR NON-INFRINGEMENT.
//
// See the Apache Version 2.0 License for specific language governing permissions
// and limitations under the License.

// TODO: Verify that this is is still needed..
#define NTDDI_VERSION 0x06010000

#include <v8.h>
#include "nan.h"
#include <string>
#include <ppltasks.h>
#include "CollectionsConverter.h"
#include "CollectionsWrap.h"
#include "node-async.h"
#include "NodeRtUtils.h"
#include "OpaqueWrapper.h"
#include "WrapperBase.h"

#using <Windows.WinMD>

// this undefs fixes the issues of compiling Windows.Data.Json, Windows.Storag.FileProperties, and Windows.Stroage.Search
// Some of the node header files brings windows definitions with the same names as some of the WinRT methods
#undef DocumentProperties
#undef GetObject
#undef CreateEvent
#undef FindText
#undef SendMessage

const char* REGISTRATION_TOKEN_MAP_PROPERTY_NAME = "__registrationTokenMap__";

using v8::Array;
using v8::String;
using v8::Value;
using v8::Boolean;
using v8::Integer;
using v8::FunctionTemplate;
using v8::Object;
using v8::Local;
using v8::Function;
using v8::Date;
using v8::Number;
using v8::PropertyAttribute;
using v8::Primitive;
using Nan::HandleScope;
using Nan::Persistent;
using Nan::Undefined;
using Nan::True;
using Nan::False;
using Nan::Null;
using Nan::MaybeLocal;
using Nan::EscapableHandleScope;
using Nan::HandleScope;
using Nan::TryCatch;
using namespace concurrency;

namespace NodeRT { namespace Windows { namespace Perception { namespace Spatial { namespace Surfaces { 
  v8::Local<v8::Value> WrapSpatialSurfaceInfo(::Windows::Perception::Spatial::Surfaces::SpatialSurfaceInfo^ wintRtInstance);
  ::Windows::Perception::Spatial::Surfaces::SpatialSurfaceInfo^ UnwrapSpatialSurfaceInfo(Local<Value> value);
  
  v8::Local<v8::Value> WrapSpatialSurfaceMeshBuffer(::Windows::Perception::Spatial::Surfaces::SpatialSurfaceMeshBuffer^ wintRtInstance);
  ::Windows::Perception::Spatial::Surfaces::SpatialSurfaceMeshBuffer^ UnwrapSpatialSurfaceMeshBuffer(Local<Value> value);
  
  v8::Local<v8::Value> WrapSpatialSurfaceMesh(::Windows::Perception::Spatial::Surfaces::SpatialSurfaceMesh^ wintRtInstance);
  ::Windows::Perception::Spatial::Surfaces::SpatialSurfaceMesh^ UnwrapSpatialSurfaceMesh(Local<Value> value);
  
  v8::Local<v8::Value> WrapSpatialSurfaceMeshOptions(::Windows::Perception::Spatial::Surfaces::SpatialSurfaceMeshOptions^ wintRtInstance);
  ::Windows::Perception::Spatial::Surfaces::SpatialSurfaceMeshOptions^ UnwrapSpatialSurfaceMeshOptions(Local<Value> value);
  
  v8::Local<v8::Value> WrapSpatialSurfaceObserver(::Windows::Perception::Spatial::Surfaces::SpatialSurfaceObserver^ wintRtInstance);
  ::Windows::Perception::Spatial::Surfaces::SpatialSurfaceObserver^ UnwrapSpatialSurfaceObserver(Local<Value> value);
  




  static bool IsSpatialBoundingOrientedBoxJsObject(Local<Value> value) {
    if (!value->IsObject()) {
      return false;
    }

    Local<String> symbol;
    Local<Object> obj = Nan::To<Object>(value).ToLocalChecked();

    symbol = Nan::New<String>("center").ToLocalChecked();
    if (Nan::Has(obj, symbol).FromMaybe(false)) {
      if (!IsVector3JsObject(Nan::Get(obj,symbol).ToLocalChecked())) {
        return false;
      }
    }
    
    symbol = Nan::New<String>("extents").ToLocalChecked();
    if (Nan::Has(obj, symbol).FromMaybe(false)) {
      if (!IsVector3JsObject(Nan::Get(obj,symbol).ToLocalChecked())) {
        return false;
      }
    }
    
    symbol = Nan::New<String>("orientation").ToLocalChecked();
    if (Nan::Has(obj, symbol).FromMaybe(false)) {
      if (!IsQuaternionJsObject(Nan::Get(obj,symbol).ToLocalChecked())) {
        return false;
      }
    }
    
    return true;
  }

  ::Windows::Perception::Spatial::SpatialBoundingOrientedBox SpatialBoundingOrientedBoxFromJsObject(Local<Value> value) {
    HandleScope scope;
    ::Windows::Perception::Spatial::SpatialBoundingOrientedBox returnValue;

    if (!value->IsObject()) {
      Nan::ThrowError(Nan::TypeError(NodeRT::Utils::NewString(L"Unexpected type, expected an object")));
      return returnValue;
    }

    Local<Object> obj = Nan::To<Object>(value).ToLocalChecked();
    Local<String> symbol;

    symbol = Nan::New<String>("center").ToLocalChecked();
    if (Nan::Has(obj, symbol).FromMaybe(false)) {
      returnValue.Center = Vector3FromJsObject(Nan::Get(obj,symbol).ToLocalChecked());
    }
    
    symbol = Nan::New<String>("extents").ToLocalChecked();
    if (Nan::Has(obj, symbol).FromMaybe(false)) {
      returnValue.Extents = Vector3FromJsObject(Nan::Get(obj,symbol).ToLocalChecked());
    }
    
    symbol = Nan::New<String>("orientation").ToLocalChecked();
    if (Nan::Has(obj, symbol).FromMaybe(false)) {
      returnValue.Orientation = QuaternionFromJsObject(Nan::Get(obj,symbol).ToLocalChecked());
    }
    
    return returnValue;
  }

  Local<Value> SpatialBoundingOrientedBoxToJsObject(::Windows::Perception::Spatial::SpatialBoundingOrientedBox value) {
    EscapableHandleScope scope;

    Local<Object> obj = Nan::New<Object>();

    Nan::Set(obj, Nan::New<String>("center").ToLocalChecked(), Vector3ToJsObject(value.Center));
    Nan::Set(obj, Nan::New<String>("extents").ToLocalChecked(), Vector3ToJsObject(value.Extents));
    Nan::Set(obj, Nan::New<String>("orientation").ToLocalChecked(), QuaternionToJsObject(value.Orientation));

    return scope.Escape(obj);
  }
  static bool IsVector3JsObject(Local<Value> value) {
    if (!value->IsObject()) {
      return false;
    }

    Local<String> symbol;
    Local<Object> obj = Nan::To<Object>(value).ToLocalChecked();

    symbol = Nan::New<String>("x").ToLocalChecked();
    if (Nan::Has(obj, symbol).FromMaybe(false)) {
      if (!Nan::Get(obj,symbol).ToLocalChecked()->IsNumber()) {
        return false;
      }
    }
    
    symbol = Nan::New<String>("y").ToLocalChecked();
    if (Nan::Has(obj, symbol).FromMaybe(false)) {
      if (!Nan::Get(obj,symbol).ToLocalChecked()->IsNumber()) {
        return false;
      }
    }
    
    symbol = Nan::New<String>("z").ToLocalChecked();
    if (Nan::Has(obj, symbol).FromMaybe(false)) {
      if (!Nan::Get(obj,symbol).ToLocalChecked()->IsNumber()) {
        return false;
      }
    }
    
    return true;
  }

  ::Platform::Numerics::Vector3 Vector3FromJsObject(Local<Value> value) {
    HandleScope scope;
    ::Platform::Numerics::Vector3 returnValue;

    if (!value->IsObject()) {
      Nan::ThrowError(Nan::TypeError(NodeRT::Utils::NewString(L"Unexpected type, expected an object")));
      return returnValue;
    }

    Local<Object> obj = Nan::To<Object>(value).ToLocalChecked();
    Local<String> symbol;

    symbol = Nan::New<String>("x").ToLocalChecked();
    if (Nan::Has(obj, symbol).FromMaybe(false)) {
      returnValue.X = static_cast<float>(Nan::To<double>(Nan::Get(obj,symbol).ToLocalChecked()).FromMaybe(0.0));
    }
    
    symbol = Nan::New<String>("y").ToLocalChecked();
    if (Nan::Has(obj, symbol).FromMaybe(false)) {
      returnValue.Y = static_cast<float>(Nan::To<double>(Nan::Get(obj,symbol).ToLocalChecked()).FromMaybe(0.0));
    }
    
    symbol = Nan::New<String>("z").ToLocalChecked();
    if (Nan::Has(obj, symbol).FromMaybe(false)) {
      returnValue.Z = static_cast<float>(Nan::To<double>(Nan::Get(obj,symbol).ToLocalChecked()).FromMaybe(0.0));
    }
    
    return returnValue;
  }

  Local<Value> Vector3ToJsObject(::Platform::Numerics::Vector3 value) {
    EscapableHandleScope scope;

    Local<Object> obj = Nan::New<Object>();

    Nan::Set(obj, Nan::New<String>("x").ToLocalChecked(), Nan::New<Number>(static_cast<double>(value.X)));
    Nan::Set(obj, Nan::New<String>("y").ToLocalChecked(), Nan::New<Number>(static_cast<double>(value.Y)));
    Nan::Set(obj, Nan::New<String>("z").ToLocalChecked(), Nan::New<Number>(static_cast<double>(value.Z)));

    return scope.Escape(obj);
  }

  class SpatialSurfaceInfo : public WrapperBase {
    public:
      
      static void Init(const Local<Object> exports) {
        HandleScope scope;

        Local<FunctionTemplate> localRef = Nan::New<FunctionTemplate>(New);
        s_constructorTemplate.Reset(localRef);
        localRef->SetClassName(Nan::New<String>("SpatialSurfaceInfo").ToLocalChecked());
        localRef->InstanceTemplate()->SetInternalFieldCount(1);

        Local<Function> func;
        Local<FunctionTemplate> funcTemplate;

          
            Nan::SetPrototypeMethod(localRef, "tryGetBounds", TryGetBounds);
          

          
            Nan::SetPrototypeMethod(localRef, "tryComputeLatestMeshAsync", TryComputeLatestMeshAsync);
          


          
            Nan::SetAccessor(localRef->PrototypeTemplate(), Nan::New<String>("id").ToLocalChecked(), IdGetter);
            Nan::SetAccessor(localRef->PrototypeTemplate(), Nan::New<String>("updateTime").ToLocalChecked(), UpdateTimeGetter);

        Local<Object> constructor = Nan::To<Object>(Nan::GetFunction(localRef).ToLocalChecked()).ToLocalChecked();
        Nan::SetMethod(constructor, "castFrom", CastFrom);



        Nan::Set(exports, Nan::New<String>("SpatialSurfaceInfo").ToLocalChecked(), constructor);
      }

      virtual ::Platform::Object^ GetObjectInstance() const override {
        return _instance;
      }

    private:

      SpatialSurfaceInfo(::Windows::Perception::Spatial::Surfaces::SpatialSurfaceInfo^ instance) {
        _instance = instance;
      }

      
    static void New(Nan::NAN_METHOD_ARGS_TYPE info) {
      HandleScope scope;

      Local<FunctionTemplate> localRef = Nan::New<FunctionTemplate>(s_constructorTemplate);

      // in case the constructor was called without the new operator
      if (!localRef->HasInstance(info.This())) {
        if (info.Length() > 0) {
          std::unique_ptr<Local<Value> []> constructorArgs(new Local<Value>[info.Length()]);

          Local<Value> *argsPtr = constructorArgs.get();
          for (int i = 0; i < info.Length(); i++) {
            argsPtr[i] = info[i];
          }

          MaybeLocal<Object> res = Nan::NewInstance(Nan::GetFunction(localRef).ToLocalChecked(), info.Length(), constructorArgs.get());
          if (res.IsEmpty()) {
            return;
          }

          info.GetReturnValue().Set(res.ToLocalChecked());
          return;
        } else {
          MaybeLocal<Object> res = Nan::NewInstance(Nan::GetFunction(localRef).ToLocalChecked(), info.Length(), nullptr);

          if (res.IsEmpty()) {
            return;
          }

          info.GetReturnValue().Set(res.ToLocalChecked());
          return;
        }
      }

      ::Windows::Perception::Spatial::Surfaces::SpatialSurfaceInfo^ winRtInstance;


      if (info.Length() == 1 && OpaqueWrapper::IsOpaqueWrapper(info[0]) &&
        NodeRT::Utils::IsWinRtWrapperOf<::Windows::Perception::Spatial::Surfaces::SpatialSurfaceInfo^>(info[0])) {
        try {
          winRtInstance = (::Windows::Perception::Spatial::Surfaces::SpatialSurfaceInfo^) NodeRT::Utils::GetObjectInstance(info[0]);
        } catch (Platform::Exception ^exception) {
          NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
          return;
        }
      }
 else {
        Nan::ThrowError(Nan::Error(NodeRT::Utils::NewString(L"Invalid arguments, no suitable constructor found")));
        return;
      }

      NodeRT::Utils::SetHiddenValue(info.This(), Nan::New<String>("__winRtInstance__").ToLocalChecked(), True());

      SpatialSurfaceInfo *wrapperInstance = new SpatialSurfaceInfo(winRtInstance);
      wrapperInstance->Wrap(info.This());

      info.GetReturnValue().Set(info.This());
    }


      
    static void CastFrom(Nan::NAN_METHOD_ARGS_TYPE info) {
      HandleScope scope;
      if (info.Length() < 1 || !NodeRT::Utils::IsWinRtWrapperOf<::Windows::Perception::Spatial::Surfaces::SpatialSurfaceInfo^>(info[0])) {
        Nan::ThrowError(Nan::Error(NodeRT::Utils::NewString(L"Invalid arguments, no object provided, or given object could not be casted to requested type")));
        return;
      }

      ::Windows::Perception::Spatial::Surfaces::SpatialSurfaceInfo^ winRtInstance;
      try {
        winRtInstance = (::Windows::Perception::Spatial::Surfaces::SpatialSurfaceInfo^) NodeRT::Utils::GetObjectInstance(info[0]);
      } catch (Platform::Exception ^exception) {
        NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
        return;
      }

      info.GetReturnValue().Set(WrapSpatialSurfaceInfo(winRtInstance));
    }

    static void TryComputeLatestMeshAsync(Nan::NAN_METHOD_ARGS_TYPE info) {
      HandleScope scope;

      if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::Perception::Spatial::Surfaces::SpatialSurfaceInfo^>(info.This())) {
        return;
      }

      if (info.Length() == 0 || !info[info.Length() -1]->IsFunction()) {
        Nan::ThrowError(Nan::Error(NodeRT::Utils::NewString(L"Bad arguments: No callback was given")));
        return;
      }

      SpatialSurfaceInfo *wrapper = SpatialSurfaceInfo::Unwrap<SpatialSurfaceInfo>(info.This());

      ::Windows::Foundation::IAsyncOperation<::Windows::Perception::Spatial::Surfaces::SpatialSurfaceMesh^>^ op;


      if (info.Length() == 2
        && info[0]->IsNumber())
      {
        try
        {
          double arg0 = Nan::To<double>(info[0]).FromMaybe(0.0);
          
          op = wrapper->_instance->TryComputeLatestMeshAsync(arg0);
        }
        catch (Platform::Exception ^exception)
        {
          NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
          return;
        }
      }
      else if (info.Length() == 3
        && info[0]->IsNumber()
        && NodeRT::Utils::IsWinRtWrapperOf<::Windows::Perception::Spatial::Surfaces::SpatialSurfaceMeshOptions^>(info[1]))
      {
        try
        {
          double arg0 = Nan::To<double>(info[0]).FromMaybe(0.0);
          ::Windows::Perception::Spatial::Surfaces::SpatialSurfaceMeshOptions^ arg1 = UnwrapSpatialSurfaceMeshOptions(info[1]);
          
          op = wrapper->_instance->TryComputeLatestMeshAsync(arg0,arg1);
        }
        catch (Platform::Exception ^exception)
        {
          NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
          return;
        }
      }
 else {
        Nan::ThrowError(Nan::Error(NodeRT::Utils::NewString(L"Bad arguments: no suitable overload found")));
        return;
      }

      auto opTask = create_task(op);
      uv_async_t* asyncToken = NodeUtils::Async::GetAsyncToken(info[info.Length() -1].As<Function>());

      opTask.then( [asyncToken] (task<::Windows::Perception::Spatial::Surfaces::SpatialSurfaceMesh^> t) {
        try {
          auto result = t.get();
          NodeUtils::Async::RunCallbackOnMain(asyncToken, [result](NodeUtils::InvokeCallbackDelegate invokeCallback) {


            Local<Value> error;
            Local<Value> arg1;
            {
              TryCatch tryCatch;
              arg1 = WrapSpatialSurfaceMesh(result);
              if (tryCatch.HasCaught())
              {
                error = Nan::To<Object>(tryCatch.Exception()).ToLocalChecked();
              }
              else
              {
                error = Undefined();
              }
              if (arg1.IsEmpty()) arg1 = Undefined();
            }
            Local<Value> args[] = {error, arg1};


            invokeCallback(_countof(args), args);
          });
        } catch (Platform::Exception^ exception) {
          NodeUtils::Async::RunCallbackOnMain(asyncToken, [exception](NodeUtils::InvokeCallbackDelegate invokeCallback) {
            Local<Value> error = NodeRT::Utils::WinRtExceptionToJsError(exception);

            Local<Value> args[] = {error};
            invokeCallback(_countof(args), args);
          });
        }
      });
    }

    static void TryGetBounds(Nan::NAN_METHOD_ARGS_TYPE info) {
      HandleScope scope;

      if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::Perception::Spatial::Surfaces::SpatialSurfaceInfo^>(info.This())) {
        return;
      }

      SpatialSurfaceInfo *wrapper = SpatialSurfaceInfo::Unwrap<SpatialSurfaceInfo>(info.This());

      if (info.Length() == 1
        && NodeRT::Utils::IsWinRtWrapperOf<::Windows::Perception::Spatial::SpatialCoordinateSystem^>(info[0]))
      {
        try
        {
          ::Windows::Perception::Spatial::SpatialCoordinateSystem^ arg0 = dynamic_cast<::Windows::Perception::Spatial::SpatialCoordinateSystem^>(NodeRT::Utils::GetObjectInstance(info[0]));
          
          ::Platform::IBox<::Windows::Perception::Spatial::SpatialBoundingOrientedBox>^ result;
          result = wrapper->_instance->TryGetBounds(arg0);
          info.GetReturnValue().Set(result ? static_cast<Local<Value>>(SpatialBoundingOrientedBoxToJsObject(result->Value)) : Undefined());
          return;
        } catch (Platform::Exception ^exception) {
          NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
          return;
        }
      }
 else {
        Nan::ThrowError(Nan::Error(NodeRT::Utils::NewString(L"Bad arguments: no suitable overload found")));
        return;
      }
    }



    static void IdGetter(Local<String> property, const Nan::PropertyCallbackInfo<v8::Value> &info) {
      HandleScope scope;

      if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::Perception::Spatial::Surfaces::SpatialSurfaceInfo^>(info.This())) {
        return;
      }

      SpatialSurfaceInfo *wrapper = SpatialSurfaceInfo::Unwrap<SpatialSurfaceInfo>(info.This());

      try  {
        ::Platform::Guid result = wrapper->_instance->Id;
        info.GetReturnValue().Set(NodeRT::Utils::GuidToJs(result));
        return;
      } catch (Platform::Exception ^exception) {
        NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
        return;
      }
    }
      
    static void UpdateTimeGetter(Local<String> property, const Nan::PropertyCallbackInfo<v8::Value> &info) {
      HandleScope scope;

      if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::Perception::Spatial::Surfaces::SpatialSurfaceInfo^>(info.This())) {
        return;
      }

      SpatialSurfaceInfo *wrapper = SpatialSurfaceInfo::Unwrap<SpatialSurfaceInfo>(info.This());

      try  {
        ::Windows::Foundation::DateTime result = wrapper->_instance->UpdateTime;
        info.GetReturnValue().Set(NodeRT::Utils::DateTimeToJS(result));
        return;
      } catch (Platform::Exception ^exception) {
        NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
        return;
      }
    }
      


    private:
      ::Windows::Perception::Spatial::Surfaces::SpatialSurfaceInfo^ _instance;
      static Persistent<FunctionTemplate> s_constructorTemplate;

      friend v8::Local<v8::Value> WrapSpatialSurfaceInfo(::Windows::Perception::Spatial::Surfaces::SpatialSurfaceInfo^ wintRtInstance);
      friend ::Windows::Perception::Spatial::Surfaces::SpatialSurfaceInfo^ UnwrapSpatialSurfaceInfo(Local<Value> value);
  };

  Persistent<FunctionTemplate> SpatialSurfaceInfo::s_constructorTemplate;

  v8::Local<v8::Value> WrapSpatialSurfaceInfo(::Windows::Perception::Spatial::Surfaces::SpatialSurfaceInfo^ winRtInstance) {
    EscapableHandleScope scope;

    if (winRtInstance == nullptr) {
      return scope.Escape(Undefined());
    }

    Local<Value> opaqueWrapper = CreateOpaqueWrapper(winRtInstance);
    Local<Value> args[] = {opaqueWrapper};
    Local<FunctionTemplate> localRef = Nan::New<FunctionTemplate>(SpatialSurfaceInfo::s_constructorTemplate);
    return scope.Escape(Nan::NewInstance(Nan::GetFunction(localRef).ToLocalChecked(),_countof(args), args).ToLocalChecked());
  }

  ::Windows::Perception::Spatial::Surfaces::SpatialSurfaceInfo^ UnwrapSpatialSurfaceInfo(Local<Value> value) {
     return SpatialSurfaceInfo::Unwrap<SpatialSurfaceInfo>(Nan::To<Object>(value).ToLocalChecked())->_instance;
  }

  void InitSpatialSurfaceInfo(Local<Object> exports) {
    SpatialSurfaceInfo::Init(exports);
  }

  class SpatialSurfaceMeshBuffer : public WrapperBase {
    public:
      
      static void Init(const Local<Object> exports) {
        HandleScope scope;

        Local<FunctionTemplate> localRef = Nan::New<FunctionTemplate>(New);
        s_constructorTemplate.Reset(localRef);
        localRef->SetClassName(Nan::New<String>("SpatialSurfaceMeshBuffer").ToLocalChecked());
        localRef->InstanceTemplate()->SetInternalFieldCount(1);





          
            Nan::SetAccessor(localRef->PrototypeTemplate(), Nan::New<String>("data").ToLocalChecked(), DataGetter);
            Nan::SetAccessor(localRef->PrototypeTemplate(), Nan::New<String>("elementCount").ToLocalChecked(), ElementCountGetter);
            Nan::SetAccessor(localRef->PrototypeTemplate(), Nan::New<String>("format").ToLocalChecked(), FormatGetter);
            Nan::SetAccessor(localRef->PrototypeTemplate(), Nan::New<String>("stride").ToLocalChecked(), StrideGetter);

        Local<Object> constructor = Nan::To<Object>(Nan::GetFunction(localRef).ToLocalChecked()).ToLocalChecked();
        Nan::SetMethod(constructor, "castFrom", CastFrom);



        Nan::Set(exports, Nan::New<String>("SpatialSurfaceMeshBuffer").ToLocalChecked(), constructor);
      }

      virtual ::Platform::Object^ GetObjectInstance() const override {
        return _instance;
      }

    private:

      SpatialSurfaceMeshBuffer(::Windows::Perception::Spatial::Surfaces::SpatialSurfaceMeshBuffer^ instance) {
        _instance = instance;
      }

      
    static void New(Nan::NAN_METHOD_ARGS_TYPE info) {
      HandleScope scope;

      Local<FunctionTemplate> localRef = Nan::New<FunctionTemplate>(s_constructorTemplate);

      // in case the constructor was called without the new operator
      if (!localRef->HasInstance(info.This())) {
        if (info.Length() > 0) {
          std::unique_ptr<Local<Value> []> constructorArgs(new Local<Value>[info.Length()]);

          Local<Value> *argsPtr = constructorArgs.get();
          for (int i = 0; i < info.Length(); i++) {
            argsPtr[i] = info[i];
          }

          MaybeLocal<Object> res = Nan::NewInstance(Nan::GetFunction(localRef).ToLocalChecked(), info.Length(), constructorArgs.get());
          if (res.IsEmpty()) {
            return;
          }

          info.GetReturnValue().Set(res.ToLocalChecked());
          return;
        } else {
          MaybeLocal<Object> res = Nan::NewInstance(Nan::GetFunction(localRef).ToLocalChecked(), info.Length(), nullptr);

          if (res.IsEmpty()) {
            return;
          }

          info.GetReturnValue().Set(res.ToLocalChecked());
          return;
        }
      }

      ::Windows::Perception::Spatial::Surfaces::SpatialSurfaceMeshBuffer^ winRtInstance;


      if (info.Length() == 1 && OpaqueWrapper::IsOpaqueWrapper(info[0]) &&
        NodeRT::Utils::IsWinRtWrapperOf<::Windows::Perception::Spatial::Surfaces::SpatialSurfaceMeshBuffer^>(info[0])) {
        try {
          winRtInstance = (::Windows::Perception::Spatial::Surfaces::SpatialSurfaceMeshBuffer^) NodeRT::Utils::GetObjectInstance(info[0]);
        } catch (Platform::Exception ^exception) {
          NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
          return;
        }
      }
 else {
        Nan::ThrowError(Nan::Error(NodeRT::Utils::NewString(L"Invalid arguments, no suitable constructor found")));
        return;
      }

      NodeRT::Utils::SetHiddenValue(info.This(), Nan::New<String>("__winRtInstance__").ToLocalChecked(), True());

      SpatialSurfaceMeshBuffer *wrapperInstance = new SpatialSurfaceMeshBuffer(winRtInstance);
      wrapperInstance->Wrap(info.This());

      info.GetReturnValue().Set(info.This());
    }


      
    static void CastFrom(Nan::NAN_METHOD_ARGS_TYPE info) {
      HandleScope scope;
      if (info.Length() < 1 || !NodeRT::Utils::IsWinRtWrapperOf<::Windows::Perception::Spatial::Surfaces::SpatialSurfaceMeshBuffer^>(info[0])) {
        Nan::ThrowError(Nan::Error(NodeRT::Utils::NewString(L"Invalid arguments, no object provided, or given object could not be casted to requested type")));
        return;
      }

      ::Windows::Perception::Spatial::Surfaces::SpatialSurfaceMeshBuffer^ winRtInstance;
      try {
        winRtInstance = (::Windows::Perception::Spatial::Surfaces::SpatialSurfaceMeshBuffer^) NodeRT::Utils::GetObjectInstance(info[0]);
      } catch (Platform::Exception ^exception) {
        NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
        return;
      }

      info.GetReturnValue().Set(WrapSpatialSurfaceMeshBuffer(winRtInstance));
    }





    static void DataGetter(Local<String> property, const Nan::PropertyCallbackInfo<v8::Value> &info) {
      HandleScope scope;

      if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::Perception::Spatial::Surfaces::SpatialSurfaceMeshBuffer^>(info.This())) {
        return;
      }

      SpatialSurfaceMeshBuffer *wrapper = SpatialSurfaceMeshBuffer::Unwrap<SpatialSurfaceMeshBuffer>(info.This());

      try  {
        ::Windows::Storage::Streams::IBuffer^ result = wrapper->_instance->Data;
        info.GetReturnValue().Set(NodeRT::Utils::CreateExternalWinRTObject("Windows.Storage.Streams", "IBuffer", result));
        return;
      } catch (Platform::Exception ^exception) {
        NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
        return;
      }
    }
      
    static void ElementCountGetter(Local<String> property, const Nan::PropertyCallbackInfo<v8::Value> &info) {
      HandleScope scope;

      if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::Perception::Spatial::Surfaces::SpatialSurfaceMeshBuffer^>(info.This())) {
        return;
      }

      SpatialSurfaceMeshBuffer *wrapper = SpatialSurfaceMeshBuffer::Unwrap<SpatialSurfaceMeshBuffer>(info.This());

      try  {
        unsigned int result = wrapper->_instance->ElementCount;
        info.GetReturnValue().Set(Nan::New<Integer>(result));
        return;
      } catch (Platform::Exception ^exception) {
        NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
        return;
      }
    }
      
    static void FormatGetter(Local<String> property, const Nan::PropertyCallbackInfo<v8::Value> &info) {
      HandleScope scope;

      if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::Perception::Spatial::Surfaces::SpatialSurfaceMeshBuffer^>(info.This())) {
        return;
      }

      SpatialSurfaceMeshBuffer *wrapper = SpatialSurfaceMeshBuffer::Unwrap<SpatialSurfaceMeshBuffer>(info.This());

      try  {
        ::Windows::Graphics::DirectX::DirectXPixelFormat result = wrapper->_instance->Format;
        info.GetReturnValue().Set(Nan::New<Integer>(static_cast<int>(result)));
        return;
      } catch (Platform::Exception ^exception) {
        NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
        return;
      }
    }
      
    static void StrideGetter(Local<String> property, const Nan::PropertyCallbackInfo<v8::Value> &info) {
      HandleScope scope;

      if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::Perception::Spatial::Surfaces::SpatialSurfaceMeshBuffer^>(info.This())) {
        return;
      }

      SpatialSurfaceMeshBuffer *wrapper = SpatialSurfaceMeshBuffer::Unwrap<SpatialSurfaceMeshBuffer>(info.This());

      try  {
        unsigned int result = wrapper->_instance->Stride;
        info.GetReturnValue().Set(Nan::New<Integer>(result));
        return;
      } catch (Platform::Exception ^exception) {
        NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
        return;
      }
    }
      


    private:
      ::Windows::Perception::Spatial::Surfaces::SpatialSurfaceMeshBuffer^ _instance;
      static Persistent<FunctionTemplate> s_constructorTemplate;

      friend v8::Local<v8::Value> WrapSpatialSurfaceMeshBuffer(::Windows::Perception::Spatial::Surfaces::SpatialSurfaceMeshBuffer^ wintRtInstance);
      friend ::Windows::Perception::Spatial::Surfaces::SpatialSurfaceMeshBuffer^ UnwrapSpatialSurfaceMeshBuffer(Local<Value> value);
  };

  Persistent<FunctionTemplate> SpatialSurfaceMeshBuffer::s_constructorTemplate;

  v8::Local<v8::Value> WrapSpatialSurfaceMeshBuffer(::Windows::Perception::Spatial::Surfaces::SpatialSurfaceMeshBuffer^ winRtInstance) {
    EscapableHandleScope scope;

    if (winRtInstance == nullptr) {
      return scope.Escape(Undefined());
    }

    Local<Value> opaqueWrapper = CreateOpaqueWrapper(winRtInstance);
    Local<Value> args[] = {opaqueWrapper};
    Local<FunctionTemplate> localRef = Nan::New<FunctionTemplate>(SpatialSurfaceMeshBuffer::s_constructorTemplate);
    return scope.Escape(Nan::NewInstance(Nan::GetFunction(localRef).ToLocalChecked(),_countof(args), args).ToLocalChecked());
  }

  ::Windows::Perception::Spatial::Surfaces::SpatialSurfaceMeshBuffer^ UnwrapSpatialSurfaceMeshBuffer(Local<Value> value) {
     return SpatialSurfaceMeshBuffer::Unwrap<SpatialSurfaceMeshBuffer>(Nan::To<Object>(value).ToLocalChecked())->_instance;
  }

  void InitSpatialSurfaceMeshBuffer(Local<Object> exports) {
    SpatialSurfaceMeshBuffer::Init(exports);
  }

  class SpatialSurfaceMesh : public WrapperBase {
    public:
      
      static void Init(const Local<Object> exports) {
        HandleScope scope;

        Local<FunctionTemplate> localRef = Nan::New<FunctionTemplate>(New);
        s_constructorTemplate.Reset(localRef);
        localRef->SetClassName(Nan::New<String>("SpatialSurfaceMesh").ToLocalChecked());
        localRef->InstanceTemplate()->SetInternalFieldCount(1);





          
            Nan::SetAccessor(localRef->PrototypeTemplate(), Nan::New<String>("coordinateSystem").ToLocalChecked(), CoordinateSystemGetter);
            Nan::SetAccessor(localRef->PrototypeTemplate(), Nan::New<String>("surfaceInfo").ToLocalChecked(), SurfaceInfoGetter);
            Nan::SetAccessor(localRef->PrototypeTemplate(), Nan::New<String>("triangleIndices").ToLocalChecked(), TriangleIndicesGetter);
            Nan::SetAccessor(localRef->PrototypeTemplate(), Nan::New<String>("vertexNormals").ToLocalChecked(), VertexNormalsGetter);
            Nan::SetAccessor(localRef->PrototypeTemplate(), Nan::New<String>("vertexPositionScale").ToLocalChecked(), VertexPositionScaleGetter);
            Nan::SetAccessor(localRef->PrototypeTemplate(), Nan::New<String>("vertexPositions").ToLocalChecked(), VertexPositionsGetter);

        Local<Object> constructor = Nan::To<Object>(Nan::GetFunction(localRef).ToLocalChecked()).ToLocalChecked();
        Nan::SetMethod(constructor, "castFrom", CastFrom);



        Nan::Set(exports, Nan::New<String>("SpatialSurfaceMesh").ToLocalChecked(), constructor);
      }

      virtual ::Platform::Object^ GetObjectInstance() const override {
        return _instance;
      }

    private:

      SpatialSurfaceMesh(::Windows::Perception::Spatial::Surfaces::SpatialSurfaceMesh^ instance) {
        _instance = instance;
      }

      
    static void New(Nan::NAN_METHOD_ARGS_TYPE info) {
      HandleScope scope;

      Local<FunctionTemplate> localRef = Nan::New<FunctionTemplate>(s_constructorTemplate);

      // in case the constructor was called without the new operator
      if (!localRef->HasInstance(info.This())) {
        if (info.Length() > 0) {
          std::unique_ptr<Local<Value> []> constructorArgs(new Local<Value>[info.Length()]);

          Local<Value> *argsPtr = constructorArgs.get();
          for (int i = 0; i < info.Length(); i++) {
            argsPtr[i] = info[i];
          }

          MaybeLocal<Object> res = Nan::NewInstance(Nan::GetFunction(localRef).ToLocalChecked(), info.Length(), constructorArgs.get());
          if (res.IsEmpty()) {
            return;
          }

          info.GetReturnValue().Set(res.ToLocalChecked());
          return;
        } else {
          MaybeLocal<Object> res = Nan::NewInstance(Nan::GetFunction(localRef).ToLocalChecked(), info.Length(), nullptr);

          if (res.IsEmpty()) {
            return;
          }

          info.GetReturnValue().Set(res.ToLocalChecked());
          return;
        }
      }

      ::Windows::Perception::Spatial::Surfaces::SpatialSurfaceMesh^ winRtInstance;


      if (info.Length() == 1 && OpaqueWrapper::IsOpaqueWrapper(info[0]) &&
        NodeRT::Utils::IsWinRtWrapperOf<::Windows::Perception::Spatial::Surfaces::SpatialSurfaceMesh^>(info[0])) {
        try {
          winRtInstance = (::Windows::Perception::Spatial::Surfaces::SpatialSurfaceMesh^) NodeRT::Utils::GetObjectInstance(info[0]);
        } catch (Platform::Exception ^exception) {
          NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
          return;
        }
      }
 else {
        Nan::ThrowError(Nan::Error(NodeRT::Utils::NewString(L"Invalid arguments, no suitable constructor found")));
        return;
      }

      NodeRT::Utils::SetHiddenValue(info.This(), Nan::New<String>("__winRtInstance__").ToLocalChecked(), True());

      SpatialSurfaceMesh *wrapperInstance = new SpatialSurfaceMesh(winRtInstance);
      wrapperInstance->Wrap(info.This());

      info.GetReturnValue().Set(info.This());
    }


      
    static void CastFrom(Nan::NAN_METHOD_ARGS_TYPE info) {
      HandleScope scope;
      if (info.Length() < 1 || !NodeRT::Utils::IsWinRtWrapperOf<::Windows::Perception::Spatial::Surfaces::SpatialSurfaceMesh^>(info[0])) {
        Nan::ThrowError(Nan::Error(NodeRT::Utils::NewString(L"Invalid arguments, no object provided, or given object could not be casted to requested type")));
        return;
      }

      ::Windows::Perception::Spatial::Surfaces::SpatialSurfaceMesh^ winRtInstance;
      try {
        winRtInstance = (::Windows::Perception::Spatial::Surfaces::SpatialSurfaceMesh^) NodeRT::Utils::GetObjectInstance(info[0]);
      } catch (Platform::Exception ^exception) {
        NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
        return;
      }

      info.GetReturnValue().Set(WrapSpatialSurfaceMesh(winRtInstance));
    }





    static void CoordinateSystemGetter(Local<String> property, const Nan::PropertyCallbackInfo<v8::Value> &info) {
      HandleScope scope;

      if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::Perception::Spatial::Surfaces::SpatialSurfaceMesh^>(info.This())) {
        return;
      }

      SpatialSurfaceMesh *wrapper = SpatialSurfaceMesh::Unwrap<SpatialSurfaceMesh>(info.This());

      try  {
        ::Windows::Perception::Spatial::SpatialCoordinateSystem^ result = wrapper->_instance->CoordinateSystem;
        info.GetReturnValue().Set(NodeRT::Utils::CreateExternalWinRTObject("Windows.Perception.Spatial", "SpatialCoordinateSystem", result));
        return;
      } catch (Platform::Exception ^exception) {
        NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
        return;
      }
    }
      
    static void SurfaceInfoGetter(Local<String> property, const Nan::PropertyCallbackInfo<v8::Value> &info) {
      HandleScope scope;

      if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::Perception::Spatial::Surfaces::SpatialSurfaceMesh^>(info.This())) {
        return;
      }

      SpatialSurfaceMesh *wrapper = SpatialSurfaceMesh::Unwrap<SpatialSurfaceMesh>(info.This());

      try  {
        ::Windows::Perception::Spatial::Surfaces::SpatialSurfaceInfo^ result = wrapper->_instance->SurfaceInfo;
        info.GetReturnValue().Set(WrapSpatialSurfaceInfo(result));
        return;
      } catch (Platform::Exception ^exception) {
        NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
        return;
      }
    }
      
    static void TriangleIndicesGetter(Local<String> property, const Nan::PropertyCallbackInfo<v8::Value> &info) {
      HandleScope scope;

      if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::Perception::Spatial::Surfaces::SpatialSurfaceMesh^>(info.This())) {
        return;
      }

      SpatialSurfaceMesh *wrapper = SpatialSurfaceMesh::Unwrap<SpatialSurfaceMesh>(info.This());

      try  {
        ::Windows::Perception::Spatial::Surfaces::SpatialSurfaceMeshBuffer^ result = wrapper->_instance->TriangleIndices;
        info.GetReturnValue().Set(WrapSpatialSurfaceMeshBuffer(result));
        return;
      } catch (Platform::Exception ^exception) {
        NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
        return;
      }
    }
      
    static void VertexNormalsGetter(Local<String> property, const Nan::PropertyCallbackInfo<v8::Value> &info) {
      HandleScope scope;

      if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::Perception::Spatial::Surfaces::SpatialSurfaceMesh^>(info.This())) {
        return;
      }

      SpatialSurfaceMesh *wrapper = SpatialSurfaceMesh::Unwrap<SpatialSurfaceMesh>(info.This());

      try  {
        ::Windows::Perception::Spatial::Surfaces::SpatialSurfaceMeshBuffer^ result = wrapper->_instance->VertexNormals;
        info.GetReturnValue().Set(WrapSpatialSurfaceMeshBuffer(result));
        return;
      } catch (Platform::Exception ^exception) {
        NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
        return;
      }
    }
      
    static void VertexPositionScaleGetter(Local<String> property, const Nan::PropertyCallbackInfo<v8::Value> &info) {
      HandleScope scope;

      if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::Perception::Spatial::Surfaces::SpatialSurfaceMesh^>(info.This())) {
        return;
      }

      SpatialSurfaceMesh *wrapper = SpatialSurfaceMesh::Unwrap<SpatialSurfaceMesh>(info.This());

      try  {
        ::Platform::Numerics::Vector3 result = wrapper->_instance->VertexPositionScale;
        info.GetReturnValue().Set(Vector3ToJsObject(result));
        return;
      } catch (Platform::Exception ^exception) {
        NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
        return;
      }
    }
      
    static void VertexPositionsGetter(Local<String> property, const Nan::PropertyCallbackInfo<v8::Value> &info) {
      HandleScope scope;

      if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::Perception::Spatial::Surfaces::SpatialSurfaceMesh^>(info.This())) {
        return;
      }

      SpatialSurfaceMesh *wrapper = SpatialSurfaceMesh::Unwrap<SpatialSurfaceMesh>(info.This());

      try  {
        ::Windows::Perception::Spatial::Surfaces::SpatialSurfaceMeshBuffer^ result = wrapper->_instance->VertexPositions;
        info.GetReturnValue().Set(WrapSpatialSurfaceMeshBuffer(result));
        return;
      } catch (Platform::Exception ^exception) {
        NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
        return;
      }
    }
      


    private:
      ::Windows::Perception::Spatial::Surfaces::SpatialSurfaceMesh^ _instance;
      static Persistent<FunctionTemplate> s_constructorTemplate;

      friend v8::Local<v8::Value> WrapSpatialSurfaceMesh(::Windows::Perception::Spatial::Surfaces::SpatialSurfaceMesh^ wintRtInstance);
      friend ::Windows::Perception::Spatial::Surfaces::SpatialSurfaceMesh^ UnwrapSpatialSurfaceMesh(Local<Value> value);
  };

  Persistent<FunctionTemplate> SpatialSurfaceMesh::s_constructorTemplate;

  v8::Local<v8::Value> WrapSpatialSurfaceMesh(::Windows::Perception::Spatial::Surfaces::SpatialSurfaceMesh^ winRtInstance) {
    EscapableHandleScope scope;

    if (winRtInstance == nullptr) {
      return scope.Escape(Undefined());
    }

    Local<Value> opaqueWrapper = CreateOpaqueWrapper(winRtInstance);
    Local<Value> args[] = {opaqueWrapper};
    Local<FunctionTemplate> localRef = Nan::New<FunctionTemplate>(SpatialSurfaceMesh::s_constructorTemplate);
    return scope.Escape(Nan::NewInstance(Nan::GetFunction(localRef).ToLocalChecked(),_countof(args), args).ToLocalChecked());
  }

  ::Windows::Perception::Spatial::Surfaces::SpatialSurfaceMesh^ UnwrapSpatialSurfaceMesh(Local<Value> value) {
     return SpatialSurfaceMesh::Unwrap<SpatialSurfaceMesh>(Nan::To<Object>(value).ToLocalChecked())->_instance;
  }

  void InitSpatialSurfaceMesh(Local<Object> exports) {
    SpatialSurfaceMesh::Init(exports);
  }

  class SpatialSurfaceMeshOptions : public WrapperBase {
    public:
      
      static void Init(const Local<Object> exports) {
        HandleScope scope;

        Local<FunctionTemplate> localRef = Nan::New<FunctionTemplate>(New);
        s_constructorTemplate.Reset(localRef);
        localRef->SetClassName(Nan::New<String>("SpatialSurfaceMeshOptions").ToLocalChecked());
        localRef->InstanceTemplate()->SetInternalFieldCount(1);





          
            Nan::SetAccessor(localRef->PrototypeTemplate(), Nan::New<String>("vertexPositionFormat").ToLocalChecked(), VertexPositionFormatGetter, VertexPositionFormatSetter);
            Nan::SetAccessor(localRef->PrototypeTemplate(), Nan::New<String>("vertexNormalFormat").ToLocalChecked(), VertexNormalFormatGetter, VertexNormalFormatSetter);
            Nan::SetAccessor(localRef->PrototypeTemplate(), Nan::New<String>("triangleIndexFormat").ToLocalChecked(), TriangleIndexFormatGetter, TriangleIndexFormatSetter);
            Nan::SetAccessor(localRef->PrototypeTemplate(), Nan::New<String>("includeVertexNormals").ToLocalChecked(), IncludeVertexNormalsGetter, IncludeVertexNormalsSetter);

        Local<Object> constructor = Nan::To<Object>(Nan::GetFunction(localRef).ToLocalChecked()).ToLocalChecked();
        Nan::SetMethod(constructor, "castFrom", CastFrom);

        Nan::SetAccessor(constructor, Nan::New<String>("supportedTriangleIndexFormats").ToLocalChecked(), SupportedTriangleIndexFormatsGetter);
        Nan::SetAccessor(constructor, Nan::New<String>("supportedVertexNormalFormats").ToLocalChecked(), SupportedVertexNormalFormatsGetter);
        Nan::SetAccessor(constructor, Nan::New<String>("supportedVertexPositionFormats").ToLocalChecked(), SupportedVertexPositionFormatsGetter);


        Nan::Set(exports, Nan::New<String>("SpatialSurfaceMeshOptions").ToLocalChecked(), constructor);
      }

      virtual ::Platform::Object^ GetObjectInstance() const override {
        return _instance;
      }

    private:

      SpatialSurfaceMeshOptions(::Windows::Perception::Spatial::Surfaces::SpatialSurfaceMeshOptions^ instance) {
        _instance = instance;
      }

      
    static void New(Nan::NAN_METHOD_ARGS_TYPE info) {
      HandleScope scope;

      Local<FunctionTemplate> localRef = Nan::New<FunctionTemplate>(s_constructorTemplate);

      // in case the constructor was called without the new operator
      if (!localRef->HasInstance(info.This())) {
        if (info.Length() > 0) {
          std::unique_ptr<Local<Value> []> constructorArgs(new Local<Value>[info.Length()]);

          Local<Value> *argsPtr = constructorArgs.get();
          for (int i = 0; i < info.Length(); i++) {
            argsPtr[i] = info[i];
          }

          MaybeLocal<Object> res = Nan::NewInstance(Nan::GetFunction(localRef).ToLocalChecked(), info.Length(), constructorArgs.get());
          if (res.IsEmpty()) {
            return;
          }

          info.GetReturnValue().Set(res.ToLocalChecked());
          return;
        } else {
          MaybeLocal<Object> res = Nan::NewInstance(Nan::GetFunction(localRef).ToLocalChecked(), info.Length(), nullptr);

          if (res.IsEmpty()) {
            return;
          }

          info.GetReturnValue().Set(res.ToLocalChecked());
          return;
        }
      }

      ::Windows::Perception::Spatial::Surfaces::SpatialSurfaceMeshOptions^ winRtInstance;


      if (info.Length() == 1 && OpaqueWrapper::IsOpaqueWrapper(info[0]) &&
        NodeRT::Utils::IsWinRtWrapperOf<::Windows::Perception::Spatial::Surfaces::SpatialSurfaceMeshOptions^>(info[0])) {
        try {
          winRtInstance = (::Windows::Perception::Spatial::Surfaces::SpatialSurfaceMeshOptions^) NodeRT::Utils::GetObjectInstance(info[0]);
        } catch (Platform::Exception ^exception) {
          NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
          return;
        }
      }
      else if (info.Length() == 0)
      {
        try {
          winRtInstance = ref new ::Windows::Perception::Spatial::Surfaces::SpatialSurfaceMeshOptions();
        } catch (Platform::Exception ^exception) {
          NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
          return;
        }
      }
 else {
        Nan::ThrowError(Nan::Error(NodeRT::Utils::NewString(L"Invalid arguments, no suitable constructor found")));
        return;
      }

      NodeRT::Utils::SetHiddenValue(info.This(), Nan::New<String>("__winRtInstance__").ToLocalChecked(), True());

      SpatialSurfaceMeshOptions *wrapperInstance = new SpatialSurfaceMeshOptions(winRtInstance);
      wrapperInstance->Wrap(info.This());

      info.GetReturnValue().Set(info.This());
    }


      
    static void CastFrom(Nan::NAN_METHOD_ARGS_TYPE info) {
      HandleScope scope;
      if (info.Length() < 1 || !NodeRT::Utils::IsWinRtWrapperOf<::Windows::Perception::Spatial::Surfaces::SpatialSurfaceMeshOptions^>(info[0])) {
        Nan::ThrowError(Nan::Error(NodeRT::Utils::NewString(L"Invalid arguments, no object provided, or given object could not be casted to requested type")));
        return;
      }

      ::Windows::Perception::Spatial::Surfaces::SpatialSurfaceMeshOptions^ winRtInstance;
      try {
        winRtInstance = (::Windows::Perception::Spatial::Surfaces::SpatialSurfaceMeshOptions^) NodeRT::Utils::GetObjectInstance(info[0]);
      } catch (Platform::Exception ^exception) {
        NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
        return;
      }

      info.GetReturnValue().Set(WrapSpatialSurfaceMeshOptions(winRtInstance));
    }





    static void VertexPositionFormatGetter(Local<String> property, const Nan::PropertyCallbackInfo<v8::Value> &info) {
      HandleScope scope;

      if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::Perception::Spatial::Surfaces::SpatialSurfaceMeshOptions^>(info.This())) {
        return;
      }

      SpatialSurfaceMeshOptions *wrapper = SpatialSurfaceMeshOptions::Unwrap<SpatialSurfaceMeshOptions>(info.This());

      try  {
        ::Windows::Graphics::DirectX::DirectXPixelFormat result = wrapper->_instance->VertexPositionFormat;
        info.GetReturnValue().Set(Nan::New<Integer>(static_cast<int>(result)));
        return;
      } catch (Platform::Exception ^exception) {
        NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
        return;
      }
    }
      
    static void VertexPositionFormatSetter(Local<String> property, Local<Value> value, const Nan::PropertyCallbackInfo<void> &info) {
      HandleScope scope;

      if (!value->IsInt32()) {
        Nan::ThrowError(Nan::Error(NodeRT::Utils::NewString(L"Value to set is of unexpected type")));
        return;
      }

      if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::Perception::Spatial::Surfaces::SpatialSurfaceMeshOptions^>(info.This())) {
        return;
      }

      SpatialSurfaceMeshOptions *wrapper = SpatialSurfaceMeshOptions::Unwrap<SpatialSurfaceMeshOptions>(info.This());

      try {

        ::Windows::Graphics::DirectX::DirectXPixelFormat winRtValue = static_cast<::Windows::Graphics::DirectX::DirectXPixelFormat>(Nan::To<int32_t>(value).FromMaybe(0));

        wrapper->_instance->VertexPositionFormat = winRtValue;
      } catch (Platform::Exception ^exception) {
        NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
      }
    }
      
    static void VertexNormalFormatGetter(Local<String> property, const Nan::PropertyCallbackInfo<v8::Value> &info) {
      HandleScope scope;

      if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::Perception::Spatial::Surfaces::SpatialSurfaceMeshOptions^>(info.This())) {
        return;
      }

      SpatialSurfaceMeshOptions *wrapper = SpatialSurfaceMeshOptions::Unwrap<SpatialSurfaceMeshOptions>(info.This());

      try  {
        ::Windows::Graphics::DirectX::DirectXPixelFormat result = wrapper->_instance->VertexNormalFormat;
        info.GetReturnValue().Set(Nan::New<Integer>(static_cast<int>(result)));
        return;
      } catch (Platform::Exception ^exception) {
        NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
        return;
      }
    }
      
    static void VertexNormalFormatSetter(Local<String> property, Local<Value> value, const Nan::PropertyCallbackInfo<void> &info) {
      HandleScope scope;

      if (!value->IsInt32()) {
        Nan::ThrowError(Nan::Error(NodeRT::Utils::NewString(L"Value to set is of unexpected type")));
        return;
      }

      if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::Perception::Spatial::Surfaces::SpatialSurfaceMeshOptions^>(info.This())) {
        return;
      }

      SpatialSurfaceMeshOptions *wrapper = SpatialSurfaceMeshOptions::Unwrap<SpatialSurfaceMeshOptions>(info.This());

      try {

        ::Windows::Graphics::DirectX::DirectXPixelFormat winRtValue = static_cast<::Windows::Graphics::DirectX::DirectXPixelFormat>(Nan::To<int32_t>(value).FromMaybe(0));

        wrapper->_instance->VertexNormalFormat = winRtValue;
      } catch (Platform::Exception ^exception) {
        NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
      }
    }
      
    static void TriangleIndexFormatGetter(Local<String> property, const Nan::PropertyCallbackInfo<v8::Value> &info) {
      HandleScope scope;

      if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::Perception::Spatial::Surfaces::SpatialSurfaceMeshOptions^>(info.This())) {
        return;
      }

      SpatialSurfaceMeshOptions *wrapper = SpatialSurfaceMeshOptions::Unwrap<SpatialSurfaceMeshOptions>(info.This());

      try  {
        ::Windows::Graphics::DirectX::DirectXPixelFormat result = wrapper->_instance->TriangleIndexFormat;
        info.GetReturnValue().Set(Nan::New<Integer>(static_cast<int>(result)));
        return;
      } catch (Platform::Exception ^exception) {
        NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
        return;
      }
    }
      
    static void TriangleIndexFormatSetter(Local<String> property, Local<Value> value, const Nan::PropertyCallbackInfo<void> &info) {
      HandleScope scope;

      if (!value->IsInt32()) {
        Nan::ThrowError(Nan::Error(NodeRT::Utils::NewString(L"Value to set is of unexpected type")));
        return;
      }

      if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::Perception::Spatial::Surfaces::SpatialSurfaceMeshOptions^>(info.This())) {
        return;
      }

      SpatialSurfaceMeshOptions *wrapper = SpatialSurfaceMeshOptions::Unwrap<SpatialSurfaceMeshOptions>(info.This());

      try {

        ::Windows::Graphics::DirectX::DirectXPixelFormat winRtValue = static_cast<::Windows::Graphics::DirectX::DirectXPixelFormat>(Nan::To<int32_t>(value).FromMaybe(0));

        wrapper->_instance->TriangleIndexFormat = winRtValue;
      } catch (Platform::Exception ^exception) {
        NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
      }
    }
      
    static void IncludeVertexNormalsGetter(Local<String> property, const Nan::PropertyCallbackInfo<v8::Value> &info) {
      HandleScope scope;

      if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::Perception::Spatial::Surfaces::SpatialSurfaceMeshOptions^>(info.This())) {
        return;
      }

      SpatialSurfaceMeshOptions *wrapper = SpatialSurfaceMeshOptions::Unwrap<SpatialSurfaceMeshOptions>(info.This());

      try  {
        bool result = wrapper->_instance->IncludeVertexNormals;
        info.GetReturnValue().Set(Nan::New<Boolean>(result));
        return;
      } catch (Platform::Exception ^exception) {
        NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
        return;
      }
    }
      
    static void IncludeVertexNormalsSetter(Local<String> property, Local<Value> value, const Nan::PropertyCallbackInfo<void> &info) {
      HandleScope scope;

      if (!value->IsBoolean()) {
        Nan::ThrowError(Nan::Error(NodeRT::Utils::NewString(L"Value to set is of unexpected type")));
        return;
      }

      if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::Perception::Spatial::Surfaces::SpatialSurfaceMeshOptions^>(info.This())) {
        return;
      }

      SpatialSurfaceMeshOptions *wrapper = SpatialSurfaceMeshOptions::Unwrap<SpatialSurfaceMeshOptions>(info.This());

      try {

        bool winRtValue = Nan::To<bool>(value).FromMaybe(false);

        wrapper->_instance->IncludeVertexNormals = winRtValue;
      } catch (Platform::Exception ^exception) {
        NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
      }
    }
      


    static void SupportedTriangleIndexFormatsGetter(Local<String> property, const Nan::PropertyCallbackInfo<v8::Value> &info) {
      HandleScope scope;

      try
      {
        ::Windows::Foundation::Collections::IVectorView<::Windows::Graphics::DirectX::DirectXPixelFormat>^ result = ::Windows::Perception::Spatial::Surfaces::SpatialSurfaceMeshOptions::SupportedTriangleIndexFormats;
        info.GetReturnValue().Set(NodeRT::Collections::VectorViewWrapper<::Windows::Graphics::DirectX::DirectXPixelFormat>::CreateVectorViewWrapper(result, 
            [](::Windows::Graphics::DirectX::DirectXPixelFormat val) -> Local<Value> {
              return Nan::New<Integer>(static_cast<int>(val));
            },
            [](Local<Value> value) -> bool {
              return value->IsInt32();
            },
            [](Local<Value> value) -> ::Windows::Graphics::DirectX::DirectXPixelFormat {
              return static_cast<::Windows::Graphics::DirectX::DirectXPixelFormat>(Nan::To<int32_t>(value).FromMaybe(0));
            }
          ));
        return;
      } catch (Platform::Exception ^exception) {
        NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
        return;
      }
    }
      

    static void SupportedVertexNormalFormatsGetter(Local<String> property, const Nan::PropertyCallbackInfo<v8::Value> &info) {
      HandleScope scope;

      try
      {
        ::Windows::Foundation::Collections::IVectorView<::Windows::Graphics::DirectX::DirectXPixelFormat>^ result = ::Windows::Perception::Spatial::Surfaces::SpatialSurfaceMeshOptions::SupportedVertexNormalFormats;
        info.GetReturnValue().Set(NodeRT::Collections::VectorViewWrapper<::Windows::Graphics::DirectX::DirectXPixelFormat>::CreateVectorViewWrapper(result, 
            [](::Windows::Graphics::DirectX::DirectXPixelFormat val) -> Local<Value> {
              return Nan::New<Integer>(static_cast<int>(val));
            },
            [](Local<Value> value) -> bool {
              return value->IsInt32();
            },
            [](Local<Value> value) -> ::Windows::Graphics::DirectX::DirectXPixelFormat {
              return static_cast<::Windows::Graphics::DirectX::DirectXPixelFormat>(Nan::To<int32_t>(value).FromMaybe(0));
            }
          ));
        return;
      } catch (Platform::Exception ^exception) {
        NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
        return;
      }
    }
      

    static void SupportedVertexPositionFormatsGetter(Local<String> property, const Nan::PropertyCallbackInfo<v8::Value> &info) {
      HandleScope scope;

      try
      {
        ::Windows::Foundation::Collections::IVectorView<::Windows::Graphics::DirectX::DirectXPixelFormat>^ result = ::Windows::Perception::Spatial::Surfaces::SpatialSurfaceMeshOptions::SupportedVertexPositionFormats;
        info.GetReturnValue().Set(NodeRT::Collections::VectorViewWrapper<::Windows::Graphics::DirectX::DirectXPixelFormat>::CreateVectorViewWrapper(result, 
            [](::Windows::Graphics::DirectX::DirectXPixelFormat val) -> Local<Value> {
              return Nan::New<Integer>(static_cast<int>(val));
            },
            [](Local<Value> value) -> bool {
              return value->IsInt32();
            },
            [](Local<Value> value) -> ::Windows::Graphics::DirectX::DirectXPixelFormat {
              return static_cast<::Windows::Graphics::DirectX::DirectXPixelFormat>(Nan::To<int32_t>(value).FromMaybe(0));
            }
          ));
        return;
      } catch (Platform::Exception ^exception) {
        NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
        return;
      }
    }
      

    private:
      ::Windows::Perception::Spatial::Surfaces::SpatialSurfaceMeshOptions^ _instance;
      static Persistent<FunctionTemplate> s_constructorTemplate;

      friend v8::Local<v8::Value> WrapSpatialSurfaceMeshOptions(::Windows::Perception::Spatial::Surfaces::SpatialSurfaceMeshOptions^ wintRtInstance);
      friend ::Windows::Perception::Spatial::Surfaces::SpatialSurfaceMeshOptions^ UnwrapSpatialSurfaceMeshOptions(Local<Value> value);
  };

  Persistent<FunctionTemplate> SpatialSurfaceMeshOptions::s_constructorTemplate;

  v8::Local<v8::Value> WrapSpatialSurfaceMeshOptions(::Windows::Perception::Spatial::Surfaces::SpatialSurfaceMeshOptions^ winRtInstance) {
    EscapableHandleScope scope;

    if (winRtInstance == nullptr) {
      return scope.Escape(Undefined());
    }

    Local<Value> opaqueWrapper = CreateOpaqueWrapper(winRtInstance);
    Local<Value> args[] = {opaqueWrapper};
    Local<FunctionTemplate> localRef = Nan::New<FunctionTemplate>(SpatialSurfaceMeshOptions::s_constructorTemplate);
    return scope.Escape(Nan::NewInstance(Nan::GetFunction(localRef).ToLocalChecked(),_countof(args), args).ToLocalChecked());
  }

  ::Windows::Perception::Spatial::Surfaces::SpatialSurfaceMeshOptions^ UnwrapSpatialSurfaceMeshOptions(Local<Value> value) {
     return SpatialSurfaceMeshOptions::Unwrap<SpatialSurfaceMeshOptions>(Nan::To<Object>(value).ToLocalChecked())->_instance;
  }

  void InitSpatialSurfaceMeshOptions(Local<Object> exports) {
    SpatialSurfaceMeshOptions::Init(exports);
  }

  class SpatialSurfaceObserver : public WrapperBase {
    public:
      
      static void Init(const Local<Object> exports) {
        HandleScope scope;

        Local<FunctionTemplate> localRef = Nan::New<FunctionTemplate>(New);
        s_constructorTemplate.Reset(localRef);
        localRef->SetClassName(Nan::New<String>("SpatialSurfaceObserver").ToLocalChecked());
        localRef->InstanceTemplate()->SetInternalFieldCount(1);

        Local<Function> func;
        Local<FunctionTemplate> funcTemplate;

          
            Nan::SetPrototypeMethod(localRef, "getObservedSurfaces", GetObservedSurfaces);
            Nan::SetPrototypeMethod(localRef, "setBoundingVolume", SetBoundingVolume);
            Nan::SetPrototypeMethod(localRef, "setBoundingVolumes", SetBoundingVolumes);
          


          
          Nan::SetPrototypeMethod(localRef,"addListener", AddListener);
          Nan::SetPrototypeMethod(localRef,"on", AddListener);
          Nan::SetPrototypeMethod(localRef,"removeListener", RemoveListener);
          Nan::SetPrototypeMethod(localRef, "off", RemoveListener);


        Local<Object> constructor = Nan::To<Object>(Nan::GetFunction(localRef).ToLocalChecked()).ToLocalChecked();
        Nan::SetMethod(constructor, "castFrom", CastFrom);

        Nan::SetMethod(constructor, "isSupported", IsSupported);
        func = Nan::GetFunction(Nan::New<FunctionTemplate>(RequestAccessAsync)).ToLocalChecked();
        Nan::Set(constructor, Nan::New<String>("requestAccessAsync").ToLocalChecked(), func);


        Nan::Set(exports, Nan::New<String>("SpatialSurfaceObserver").ToLocalChecked(), constructor);
      }

      virtual ::Platform::Object^ GetObjectInstance() const override {
        return _instance;
      }

    private:

      SpatialSurfaceObserver(::Windows::Perception::Spatial::Surfaces::SpatialSurfaceObserver^ instance) {
        _instance = instance;
      }

      
    static void New(Nan::NAN_METHOD_ARGS_TYPE info) {
      HandleScope scope;

      Local<FunctionTemplate> localRef = Nan::New<FunctionTemplate>(s_constructorTemplate);

      // in case the constructor was called without the new operator
      if (!localRef->HasInstance(info.This())) {
        if (info.Length() > 0) {
          std::unique_ptr<Local<Value> []> constructorArgs(new Local<Value>[info.Length()]);

          Local<Value> *argsPtr = constructorArgs.get();
          for (int i = 0; i < info.Length(); i++) {
            argsPtr[i] = info[i];
          }

          MaybeLocal<Object> res = Nan::NewInstance(Nan::GetFunction(localRef).ToLocalChecked(), info.Length(), constructorArgs.get());
          if (res.IsEmpty()) {
            return;
          }

          info.GetReturnValue().Set(res.ToLocalChecked());
          return;
        } else {
          MaybeLocal<Object> res = Nan::NewInstance(Nan::GetFunction(localRef).ToLocalChecked(), info.Length(), nullptr);

          if (res.IsEmpty()) {
            return;
          }

          info.GetReturnValue().Set(res.ToLocalChecked());
          return;
        }
      }

      ::Windows::Perception::Spatial::Surfaces::SpatialSurfaceObserver^ winRtInstance;


      if (info.Length() == 1 && OpaqueWrapper::IsOpaqueWrapper(info[0]) &&
        NodeRT::Utils::IsWinRtWrapperOf<::Windows::Perception::Spatial::Surfaces::SpatialSurfaceObserver^>(info[0])) {
        try {
          winRtInstance = (::Windows::Perception::Spatial::Surfaces::SpatialSurfaceObserver^) NodeRT::Utils::GetObjectInstance(info[0]);
        } catch (Platform::Exception ^exception) {
          NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
          return;
        }
      }
      else if (info.Length() == 0)
      {
        try {
          winRtInstance = ref new ::Windows::Perception::Spatial::Surfaces::SpatialSurfaceObserver();
        } catch (Platform::Exception ^exception) {
          NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
          return;
        }
      }
 else {
        Nan::ThrowError(Nan::Error(NodeRT::Utils::NewString(L"Invalid arguments, no suitable constructor found")));
        return;
      }

      NodeRT::Utils::SetHiddenValue(info.This(), Nan::New<String>("__winRtInstance__").ToLocalChecked(), True());

      SpatialSurfaceObserver *wrapperInstance = new SpatialSurfaceObserver(winRtInstance);
      wrapperInstance->Wrap(info.This());

      info.GetReturnValue().Set(info.This());
    }


      
    static void CastFrom(Nan::NAN_METHOD_ARGS_TYPE info) {
      HandleScope scope;
      if (info.Length() < 1 || !NodeRT::Utils::IsWinRtWrapperOf<::Windows::Perception::Spatial::Surfaces::SpatialSurfaceObserver^>(info[0])) {
        Nan::ThrowError(Nan::Error(NodeRT::Utils::NewString(L"Invalid arguments, no object provided, or given object could not be casted to requested type")));
        return;
      }

      ::Windows::Perception::Spatial::Surfaces::SpatialSurfaceObserver^ winRtInstance;
      try {
        winRtInstance = (::Windows::Perception::Spatial::Surfaces::SpatialSurfaceObserver^) NodeRT::Utils::GetObjectInstance(info[0]);
      } catch (Platform::Exception ^exception) {
        NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
        return;
      }

      info.GetReturnValue().Set(WrapSpatialSurfaceObserver(winRtInstance));
    }


    static void GetObservedSurfaces(Nan::NAN_METHOD_ARGS_TYPE info) {
      HandleScope scope;

      if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::Perception::Spatial::Surfaces::SpatialSurfaceObserver^>(info.This())) {
        return;
      }

      SpatialSurfaceObserver *wrapper = SpatialSurfaceObserver::Unwrap<SpatialSurfaceObserver>(info.This());

      if (info.Length() == 0)
      {
        try
        {
          ::Windows::Foundation::Collections::IMapView<::Platform::Guid, ::Windows::Perception::Spatial::Surfaces::SpatialSurfaceInfo^>^ result;
          result = wrapper->_instance->GetObservedSurfaces();
          info.GetReturnValue().Set(NodeRT::Collections::MapViewWrapper<::Platform::Guid,::Windows::Perception::Spatial::Surfaces::SpatialSurfaceInfo^>::CreateMapViewWrapper(result, 
            [](::Platform::Guid val) -> Local<Value> {
              return NodeRT::Utils::GuidToJs(val);
            },
            [](Local<Value> value) -> bool {
              return NodeRT::Utils::IsGuid(value);
            },
            [](Local<Value> value) -> ::Platform::Guid {
              return NodeRT::Utils::GuidFromJs(value);
            },
            [](::Windows::Perception::Spatial::Surfaces::SpatialSurfaceInfo^ val) -> Local<Value> {
              return WrapSpatialSurfaceInfo(val);
            }
          ));
          return;
        } catch (Platform::Exception ^exception) {
          NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
          return;
        }
      }
 else {
        Nan::ThrowError(Nan::Error(NodeRT::Utils::NewString(L"Bad arguments: no suitable overload found")));
        return;
      }
    }
    static void SetBoundingVolume(Nan::NAN_METHOD_ARGS_TYPE info) {
      HandleScope scope;

      if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::Perception::Spatial::Surfaces::SpatialSurfaceObserver^>(info.This())) {
        return;
      }

      SpatialSurfaceObserver *wrapper = SpatialSurfaceObserver::Unwrap<SpatialSurfaceObserver>(info.This());

      if (info.Length() == 1
        && NodeRT::Utils::IsWinRtWrapperOf<::Windows::Perception::Spatial::SpatialBoundingVolume^>(info[0]))
      {
        try
        {
          ::Windows::Perception::Spatial::SpatialBoundingVolume^ arg0 = dynamic_cast<::Windows::Perception::Spatial::SpatialBoundingVolume^>(NodeRT::Utils::GetObjectInstance(info[0]));
          
          wrapper->_instance->SetBoundingVolume(arg0);
          return;
        } catch (Platform::Exception ^exception) {
          NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
          return;
        }
      }
 else {
        Nan::ThrowError(Nan::Error(NodeRT::Utils::NewString(L"Bad arguments: no suitable overload found")));
        return;
      }
    }
    static void SetBoundingVolumes(Nan::NAN_METHOD_ARGS_TYPE info) {
      HandleScope scope;

      if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::Perception::Spatial::Surfaces::SpatialSurfaceObserver^>(info.This())) {
        return;
      }

      SpatialSurfaceObserver *wrapper = SpatialSurfaceObserver::Unwrap<SpatialSurfaceObserver>(info.This());

      if (info.Length() == 1
        && (NodeRT::Utils::IsWinRtWrapperOf<::Windows::Foundation::Collections::IIterable<::Windows::Perception::Spatial::SpatialBoundingVolume^>^>(info[0]) || info[0]->IsArray()))
      {
        try
        {
          ::Windows::Foundation::Collections::IIterable<::Windows::Perception::Spatial::SpatialBoundingVolume^>^ arg0 = 
            [] (v8::Local<v8::Value> value) -> ::Windows::Foundation::Collections::IIterable<::Windows::Perception::Spatial::SpatialBoundingVolume^>^
            {
              if (value->IsArray())
              {
                return NodeRT::Collections::JsArrayToWinrtVector<::Windows::Perception::Spatial::SpatialBoundingVolume^>(value.As<Array>(), 
                 [](Local<Value> value) -> bool {
                   return NodeRT::Utils::IsWinRtWrapperOf<::Windows::Perception::Spatial::SpatialBoundingVolume^>(value);
                 },
                 [](Local<Value> value) -> ::Windows::Perception::Spatial::SpatialBoundingVolume^ {
                   return dynamic_cast<::Windows::Perception::Spatial::SpatialBoundingVolume^>(NodeRT::Utils::GetObjectInstance(value));
                 }
                );
              }
              else
              {
                return dynamic_cast<::Windows::Foundation::Collections::IIterable<::Windows::Perception::Spatial::SpatialBoundingVolume^>^>(NodeRT::Utils::GetObjectInstance(value));
              }
            } (info[0]);
          
          wrapper->_instance->SetBoundingVolumes(arg0);
          return;
        } catch (Platform::Exception ^exception) {
          NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
          return;
        }
      }
 else {
        Nan::ThrowError(Nan::Error(NodeRT::Utils::NewString(L"Bad arguments: no suitable overload found")));
        return;
      }
    }


    static void RequestAccessAsync(Nan::NAN_METHOD_ARGS_TYPE info) {
      HandleScope scope;

      if (info.Length() == 0 || !info[info.Length() -1]->IsFunction()) {
        Nan::ThrowError(Nan::Error(NodeRT::Utils::NewString(L"Bad arguments: No callback was given")));
        return;
      }

      ::Windows::Foundation::IAsyncOperation<::Windows::Perception::Spatial::SpatialPerceptionAccessStatus>^ op;


      if (info.Length() == 1)
      {
        try
        {
          op = ::Windows::Perception::Spatial::Surfaces::SpatialSurfaceObserver::RequestAccessAsync();
        } catch (Platform::Exception ^exception) {
            NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
            return;
        }
      }
 else {
        Nan::ThrowError(Nan::Error(NodeRT::Utils::NewString(L"Bad arguments: no suitable overload found")));
        return;
      }

      auto opTask = create_task(op);
      uv_async_t* asyncToken = NodeUtils::Async::GetAsyncToken(info[info.Length() -1].As<Function>());

      opTask.then( [asyncToken] (task<::Windows::Perception::Spatial::SpatialPerceptionAccessStatus> t)
      {
        try {
          auto result = t.get();
          NodeUtils::Async::RunCallbackOnMain(asyncToken, [result](NodeUtils::InvokeCallbackDelegate invokeCallback) {


            Local<Value> error;
            Local<Value> arg1;
            {
              TryCatch tryCatch;
              arg1 = Nan::New<Integer>(static_cast<int>(result));
              if (tryCatch.HasCaught())
              {
                error = Nan::To<Object>(tryCatch.Exception()).ToLocalChecked();
              }
              else
              {
                error = Undefined();
              }
              if (arg1.IsEmpty()) arg1 = Undefined();
            }
            Local<Value> args[] = {error, arg1};


            invokeCallback(_countof(args), args);
          });
        }
        catch (Platform::Exception^ exception)
        {
          NodeUtils::Async::RunCallbackOnMain(asyncToken, [exception](NodeUtils::InvokeCallbackDelegate invokeCallback) {

            Local<Value> error = NodeRT::Utils::WinRtExceptionToJsError(exception);

            Local<Value> args[] = {error};
            invokeCallback(_countof(args), args);
          });
        }
      });
    }


    static void IsSupported(Nan::NAN_METHOD_ARGS_TYPE info) {
      HandleScope scope;

      if (info.Length() == 0)
      {
        try
        {
          bool result;
          result = ::Windows::Perception::Spatial::Surfaces::SpatialSurfaceObserver::IsSupported();
          info.GetReturnValue().Set(Nan::New<Boolean>(result));
          return;
        }
        catch (Platform::Exception ^exception)
        {
          NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
          return;
        }
      }
 else  {
        Nan::ThrowError(Nan::Error(NodeRT::Utils::NewString(L"Bad arguments: no suitable overload found")));
        return;
      }
    }



    static void AddListener(Nan::NAN_METHOD_ARGS_TYPE info) {
      HandleScope scope;

      if (info.Length() < 2 || !info[0]->IsString() || !info[1]->IsFunction()) {
        Nan::ThrowError(Nan::Error(NodeRT::Utils::NewString(L"wrong arguments, expected arguments are eventName(string),callback(function)")));
        return;
      }

      String::Value eventName(v8::Isolate::GetCurrent(), info[0]);
      auto str = *eventName;

      Local<Function> callback = info[1].As<Function>();

      ::Windows::Foundation::EventRegistrationToken registrationToken;
      if (NodeRT::Utils::CaseInsenstiveEquals(L"observedSurfacesChanged", str))
      {
        if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::Perception::Spatial::Surfaces::SpatialSurfaceObserver^>(info.This()))
        {
          Nan::ThrowError(Nan::Error(NodeRT::Utils::NewString(L"The caller of this method isn't of the expected type or internal WinRt object was disposed")));
      return;
        }
        SpatialSurfaceObserver *wrapper = SpatialSurfaceObserver::Unwrap<SpatialSurfaceObserver>(info.This());
      
        try {
          Persistent<Object>* perstPtr = new Persistent<Object>();
          perstPtr->Reset(NodeRT::Utils::CreateCallbackObjectInDomain(callback));
          std::shared_ptr<Persistent<Object>> callbackObjPtr(perstPtr,
            [] (Persistent<Object> *ptr ) {
              NodeUtils::Async::RunOnMain([ptr]() {
                ptr->Reset();
                delete ptr;
            });
          });

          registrationToken = wrapper->_instance->ObservedSurfacesChanged::add(
            ref new ::Windows::Foundation::TypedEventHandler<::Windows::Perception::Spatial::Surfaces::SpatialSurfaceObserver^, ::Platform::Object^>(
            [callbackObjPtr](::Windows::Perception::Spatial::Surfaces::SpatialSurfaceObserver^ arg0, ::Platform::Object^ arg1) {
              NodeUtils::Async::RunOnMain([callbackObjPtr , arg0, arg1]() {
                HandleScope scope;


                Local<Value> wrappedArg0;
                Local<Value> wrappedArg1;

                {
                  TryCatch tryCatch;


                  wrappedArg0 = WrapSpatialSurfaceObserver(arg0);
                  wrappedArg1 = CreateOpaqueWrapper(arg1);


                  if (wrappedArg0.IsEmpty()) wrappedArg0 = Undefined();
                  if (wrappedArg1.IsEmpty()) wrappedArg1 = Undefined();
                }

                Local<Value> args[] = { wrappedArg0, wrappedArg1 };
                Local<Object> callbackObjLocalRef = Nan::New<Object>(*callbackObjPtr);
                NodeRT::Utils::CallCallbackInDomain(callbackObjLocalRef, _countof(args), args);
              });
            })
          );
        }
        catch (Platform::Exception ^exception) {
          NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
          return;
        }

      }
 else  {
        Nan::ThrowError(Nan::Error(String::Concat(v8::Isolate::GetCurrent(), NodeRT::Utils::NewString(L"given event name isn't supported: "), info[0].As<String>())));
        return;
      }

      Local<Value> tokenMapVal = NodeRT::Utils::GetHiddenValue(callback, Nan::New<String>(REGISTRATION_TOKEN_MAP_PROPERTY_NAME).ToLocalChecked());
      Local<Object> tokenMap;

      if (tokenMapVal.IsEmpty() || Nan::Equals(tokenMapVal, Undefined()).FromMaybe(false)) {
        tokenMap = Nan::New<Object>();
        NodeRT::Utils::SetHiddenValueWithObject(callback, Nan::New<String>(REGISTRATION_TOKEN_MAP_PROPERTY_NAME).ToLocalChecked(), tokenMap);
      } else {
        tokenMap = Nan::To<Object>(tokenMapVal).ToLocalChecked();
      }

      Nan::Set(tokenMap, info[0], CreateOpaqueWrapper(::Windows::Foundation::PropertyValue::CreateInt64(registrationToken.Value)));
    }

    static void RemoveListener(Nan::NAN_METHOD_ARGS_TYPE info) {
      HandleScope scope;

      if (info.Length() < 2 || !info[0]->IsString() || !info[1]->IsFunction()) {
        Nan::ThrowError(Nan::Error(NodeRT::Utils::NewString(L"wrong arguments, expected a string and a callback")));
        return;
      }

      String::Value eventName(v8::Isolate::GetCurrent(), info[0]);
      auto str = *eventName;

      if ((!NodeRT::Utils::CaseInsenstiveEquals(L"observedSurfacesChanged", str))) {
        Nan::ThrowError(Nan::Error(String::Concat(v8::Isolate::GetCurrent(), NodeRT::Utils::NewString(L"given event name isn't supported: "), info[0].As<String>())));
        return;
      }

      Local<Function> callback = info[1].As<Function>();
      Local<Value> tokenMap = NodeRT::Utils::GetHiddenValue(callback, Nan::New<String>(REGISTRATION_TOKEN_MAP_PROPERTY_NAME).ToLocalChecked());

      if (tokenMap.IsEmpty() || Nan::Equals(tokenMap, Undefined()).FromMaybe(false)) {
        return;
      }

      Local<Value> opaqueWrapperObj =  Nan::Get(Nan::To<Object>(tokenMap).ToLocalChecked(), info[0]).ToLocalChecked();

      if (opaqueWrapperObj.IsEmpty() || Nan::Equals(opaqueWrapperObj,Undefined()).FromMaybe(false)) {
        return;
      }

      OpaqueWrapper *opaqueWrapper = OpaqueWrapper::Unwrap<OpaqueWrapper>(opaqueWrapperObj.As<Object>());

      long long tokenValue = (long long) opaqueWrapper->GetObjectInstance();
      ::Windows::Foundation::EventRegistrationToken registrationToken;
      registrationToken.Value = tokenValue;

      try  {
        if (NodeRT::Utils::CaseInsenstiveEquals(L"observedSurfacesChanged", str)) {
          if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::Perception::Spatial::Surfaces::SpatialSurfaceObserver^>(info.This()))
          {
            Nan::ThrowError(Nan::Error(NodeRT::Utils::NewString(L"The caller of this method isn't of the expected type or internal WinRt object was disposed")));
            return;
          }
          SpatialSurfaceObserver *wrapper = SpatialSurfaceObserver::Unwrap<SpatialSurfaceObserver>(info.This());
          wrapper->_instance->ObservedSurfacesChanged::remove(registrationToken);
        }
      } catch (Platform::Exception ^exception) {
        NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
      }

      Nan::Delete(Nan::To<Object>(tokenMap).ToLocalChecked(), Nan::To<String>(info[0]).ToLocalChecked());
    }
    private:
      ::Windows::Perception::Spatial::Surfaces::SpatialSurfaceObserver^ _instance;
      static Persistent<FunctionTemplate> s_constructorTemplate;

      friend v8::Local<v8::Value> WrapSpatialSurfaceObserver(::Windows::Perception::Spatial::Surfaces::SpatialSurfaceObserver^ wintRtInstance);
      friend ::Windows::Perception::Spatial::Surfaces::SpatialSurfaceObserver^ UnwrapSpatialSurfaceObserver(Local<Value> value);
  };

  Persistent<FunctionTemplate> SpatialSurfaceObserver::s_constructorTemplate;

  v8::Local<v8::Value> WrapSpatialSurfaceObserver(::Windows::Perception::Spatial::Surfaces::SpatialSurfaceObserver^ winRtInstance) {
    EscapableHandleScope scope;

    if (winRtInstance == nullptr) {
      return scope.Escape(Undefined());
    }

    Local<Value> opaqueWrapper = CreateOpaqueWrapper(winRtInstance);
    Local<Value> args[] = {opaqueWrapper};
    Local<FunctionTemplate> localRef = Nan::New<FunctionTemplate>(SpatialSurfaceObserver::s_constructorTemplate);
    return scope.Escape(Nan::NewInstance(Nan::GetFunction(localRef).ToLocalChecked(),_countof(args), args).ToLocalChecked());
  }

  ::Windows::Perception::Spatial::Surfaces::SpatialSurfaceObserver^ UnwrapSpatialSurfaceObserver(Local<Value> value) {
     return SpatialSurfaceObserver::Unwrap<SpatialSurfaceObserver>(Nan::To<Object>(value).ToLocalChecked())->_instance;
  }

  void InitSpatialSurfaceObserver(Local<Object> exports) {
    SpatialSurfaceObserver::Init(exports);
  }


} } } } } 

NAN_MODULE_INIT(init) {
  // We ignore failures for now since it probably means that
  // the initialization already happened for STA, and that's cool

  CoInitializeEx(nullptr, COINIT_MULTITHREADED);

  /*
  if (FAILED(CoInitializeEx(nullptr, COINIT_MULTITHREADED))) {
    Nan::ThrowError(Nan::Error(NodeRT::Utils::NewString(L"error in CoInitializeEx()")));
    return;
  }
  */

      NodeRT::Windows::Perception::Spatial::Surfaces::InitSpatialSurfaceInfo(target);
      NodeRT::Windows::Perception::Spatial::Surfaces::InitSpatialSurfaceMeshBuffer(target);
      NodeRT::Windows::Perception::Spatial::Surfaces::InitSpatialSurfaceMesh(target);
      NodeRT::Windows::Perception::Spatial::Surfaces::InitSpatialSurfaceMeshOptions(target);
      NodeRT::Windows::Perception::Spatial::Surfaces::InitSpatialSurfaceObserver(target);


  NodeRT::Utils::RegisterNameSpace("Windows.Perception.Spatial.Surfaces", target);
}



NODE_MODULE(binding, init)
