// 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 Devices { namespace Haptics { 
  v8::Local<v8::Value> WrapKnownSimpleHapticsControllerWaveforms(::Windows::Devices::Haptics::KnownSimpleHapticsControllerWaveforms^ wintRtInstance);
  ::Windows::Devices::Haptics::KnownSimpleHapticsControllerWaveforms^ UnwrapKnownSimpleHapticsControllerWaveforms(Local<Value> value);
  
  v8::Local<v8::Value> WrapSimpleHapticsController(::Windows::Devices::Haptics::SimpleHapticsController^ wintRtInstance);
  ::Windows::Devices::Haptics::SimpleHapticsController^ UnwrapSimpleHapticsController(Local<Value> value);
  
  v8::Local<v8::Value> WrapSimpleHapticsControllerFeedback(::Windows::Devices::Haptics::SimpleHapticsControllerFeedback^ wintRtInstance);
  ::Windows::Devices::Haptics::SimpleHapticsControllerFeedback^ UnwrapSimpleHapticsControllerFeedback(Local<Value> value);
  
  v8::Local<v8::Value> WrapVibrationDevice(::Windows::Devices::Haptics::VibrationDevice^ wintRtInstance);
  ::Windows::Devices::Haptics::VibrationDevice^ UnwrapVibrationDevice(Local<Value> value);
  



  static void InitVibrationAccessStatusEnum(const Local<Object> exports) {
    HandleScope scope;

    Local<Object> enumObject = Nan::New<Object>();

    Nan::Set(exports, Nan::New<String>("VibrationAccessStatus").ToLocalChecked(), enumObject);
    Nan::Set(enumObject, Nan::New<String>("allowed").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::Devices::Haptics::VibrationAccessStatus::Allowed)));
    Nan::Set(enumObject, Nan::New<String>("deniedByUser").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::Devices::Haptics::VibrationAccessStatus::DeniedByUser)));
    Nan::Set(enumObject, Nan::New<String>("deniedBySystem").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::Devices::Haptics::VibrationAccessStatus::DeniedBySystem)));
    Nan::Set(enumObject, Nan::New<String>("deniedByEnergySaver").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::Devices::Haptics::VibrationAccessStatus::DeniedByEnergySaver)));
  }



  class KnownSimpleHapticsControllerWaveforms : 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>("KnownSimpleHapticsControllerWaveforms").ToLocalChecked());
        localRef->InstanceTemplate()->SetInternalFieldCount(1);






        Local<Object> constructor = Nan::To<Object>(Nan::GetFunction(localRef).ToLocalChecked()).ToLocalChecked();
        Nan::SetMethod(constructor, "castFrom", CastFrom);

        Nan::SetAccessor(constructor, Nan::New<String>("buzzContinuous").ToLocalChecked(), BuzzContinuousGetter);
        Nan::SetAccessor(constructor, Nan::New<String>("click").ToLocalChecked(), ClickGetter);
        Nan::SetAccessor(constructor, Nan::New<String>("press").ToLocalChecked(), PressGetter);
        Nan::SetAccessor(constructor, Nan::New<String>("release").ToLocalChecked(), ReleaseGetter);
        Nan::SetAccessor(constructor, Nan::New<String>("rumbleContinuous").ToLocalChecked(), RumbleContinuousGetter);
        Nan::SetAccessor(constructor, Nan::New<String>("brushContinuous").ToLocalChecked(), BrushContinuousGetter);
        Nan::SetAccessor(constructor, Nan::New<String>("chiselMarkerContinuous").ToLocalChecked(), ChiselMarkerContinuousGetter);
        Nan::SetAccessor(constructor, Nan::New<String>("eraserContinuous").ToLocalChecked(), EraserContinuousGetter);
        Nan::SetAccessor(constructor, Nan::New<String>("error").ToLocalChecked(), ErrorGetter);
        Nan::SetAccessor(constructor, Nan::New<String>("galaxyPenContinuous").ToLocalChecked(), GalaxyPenContinuousGetter);
        Nan::SetAccessor(constructor, Nan::New<String>("hover").ToLocalChecked(), HoverGetter);
        Nan::SetAccessor(constructor, Nan::New<String>("inkContinuous").ToLocalChecked(), InkContinuousGetter);
        Nan::SetAccessor(constructor, Nan::New<String>("markerContinuous").ToLocalChecked(), MarkerContinuousGetter);
        Nan::SetAccessor(constructor, Nan::New<String>("pencilContinuous").ToLocalChecked(), PencilContinuousGetter);
        Nan::SetAccessor(constructor, Nan::New<String>("success").ToLocalChecked(), SuccessGetter);


        Nan::Set(exports, Nan::New<String>("KnownSimpleHapticsControllerWaveforms").ToLocalChecked(), constructor);
      }

      virtual ::Platform::Object^ GetObjectInstance() const override {
        return _instance;
      }

    private:

      KnownSimpleHapticsControllerWaveforms(::Windows::Devices::Haptics::KnownSimpleHapticsControllerWaveforms^ 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::Devices::Haptics::KnownSimpleHapticsControllerWaveforms^ winRtInstance;


      if (info.Length() == 1 && OpaqueWrapper::IsOpaqueWrapper(info[0]) &&
        NodeRT::Utils::IsWinRtWrapperOf<::Windows::Devices::Haptics::KnownSimpleHapticsControllerWaveforms^>(info[0])) {
        try {
          winRtInstance = (::Windows::Devices::Haptics::KnownSimpleHapticsControllerWaveforms^) 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());

      KnownSimpleHapticsControllerWaveforms *wrapperInstance = new KnownSimpleHapticsControllerWaveforms(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::Devices::Haptics::KnownSimpleHapticsControllerWaveforms^>(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::Devices::Haptics::KnownSimpleHapticsControllerWaveforms^ winRtInstance;
      try {
        winRtInstance = (::Windows::Devices::Haptics::KnownSimpleHapticsControllerWaveforms^) NodeRT::Utils::GetObjectInstance(info[0]);
      } catch (Platform::Exception ^exception) {
        NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
        return;
      }

      info.GetReturnValue().Set(WrapKnownSimpleHapticsControllerWaveforms(winRtInstance));
    }







    static void BuzzContinuousGetter(Local<String> property, const Nan::PropertyCallbackInfo<v8::Value> &info) {
      HandleScope scope;

      try
      {
        unsigned short result = ::Windows::Devices::Haptics::KnownSimpleHapticsControllerWaveforms::BuzzContinuous;
        info.GetReturnValue().Set(Nan::New<Integer>(result));
        return;
      } catch (Platform::Exception ^exception) {
        NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
        return;
      }
    }
      

    static void ClickGetter(Local<String> property, const Nan::PropertyCallbackInfo<v8::Value> &info) {
      HandleScope scope;

      try
      {
        unsigned short result = ::Windows::Devices::Haptics::KnownSimpleHapticsControllerWaveforms::Click;
        info.GetReturnValue().Set(Nan::New<Integer>(result));
        return;
      } catch (Platform::Exception ^exception) {
        NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
        return;
      }
    }
      

    static void PressGetter(Local<String> property, const Nan::PropertyCallbackInfo<v8::Value> &info) {
      HandleScope scope;

      try
      {
        unsigned short result = ::Windows::Devices::Haptics::KnownSimpleHapticsControllerWaveforms::Press;
        info.GetReturnValue().Set(Nan::New<Integer>(result));
        return;
      } catch (Platform::Exception ^exception) {
        NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
        return;
      }
    }
      

    static void ReleaseGetter(Local<String> property, const Nan::PropertyCallbackInfo<v8::Value> &info) {
      HandleScope scope;

      try
      {
        unsigned short result = ::Windows::Devices::Haptics::KnownSimpleHapticsControllerWaveforms::Release;
        info.GetReturnValue().Set(Nan::New<Integer>(result));
        return;
      } catch (Platform::Exception ^exception) {
        NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
        return;
      }
    }
      

    static void RumbleContinuousGetter(Local<String> property, const Nan::PropertyCallbackInfo<v8::Value> &info) {
      HandleScope scope;

      try
      {
        unsigned short result = ::Windows::Devices::Haptics::KnownSimpleHapticsControllerWaveforms::RumbleContinuous;
        info.GetReturnValue().Set(Nan::New<Integer>(result));
        return;
      } catch (Platform::Exception ^exception) {
        NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
        return;
      }
    }
      

    static void BrushContinuousGetter(Local<String> property, const Nan::PropertyCallbackInfo<v8::Value> &info) {
      HandleScope scope;

      try
      {
        unsigned short result = ::Windows::Devices::Haptics::KnownSimpleHapticsControllerWaveforms::BrushContinuous;
        info.GetReturnValue().Set(Nan::New<Integer>(result));
        return;
      } catch (Platform::Exception ^exception) {
        NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
        return;
      }
    }
      

    static void ChiselMarkerContinuousGetter(Local<String> property, const Nan::PropertyCallbackInfo<v8::Value> &info) {
      HandleScope scope;

      try
      {
        unsigned short result = ::Windows::Devices::Haptics::KnownSimpleHapticsControllerWaveforms::ChiselMarkerContinuous;
        info.GetReturnValue().Set(Nan::New<Integer>(result));
        return;
      } catch (Platform::Exception ^exception) {
        NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
        return;
      }
    }
      

    static void EraserContinuousGetter(Local<String> property, const Nan::PropertyCallbackInfo<v8::Value> &info) {
      HandleScope scope;

      try
      {
        unsigned short result = ::Windows::Devices::Haptics::KnownSimpleHapticsControllerWaveforms::EraserContinuous;
        info.GetReturnValue().Set(Nan::New<Integer>(result));
        return;
      } catch (Platform::Exception ^exception) {
        NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
        return;
      }
    }
      

    static void ErrorGetter(Local<String> property, const Nan::PropertyCallbackInfo<v8::Value> &info) {
      HandleScope scope;

      try
      {
        unsigned short result = ::Windows::Devices::Haptics::KnownSimpleHapticsControllerWaveforms::Error;
        info.GetReturnValue().Set(Nan::New<Integer>(result));
        return;
      } catch (Platform::Exception ^exception) {
        NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
        return;
      }
    }
      

    static void GalaxyPenContinuousGetter(Local<String> property, const Nan::PropertyCallbackInfo<v8::Value> &info) {
      HandleScope scope;

      try
      {
        unsigned short result = ::Windows::Devices::Haptics::KnownSimpleHapticsControllerWaveforms::GalaxyPenContinuous;
        info.GetReturnValue().Set(Nan::New<Integer>(result));
        return;
      } catch (Platform::Exception ^exception) {
        NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
        return;
      }
    }
      

    static void HoverGetter(Local<String> property, const Nan::PropertyCallbackInfo<v8::Value> &info) {
      HandleScope scope;

      try
      {
        unsigned short result = ::Windows::Devices::Haptics::KnownSimpleHapticsControllerWaveforms::Hover;
        info.GetReturnValue().Set(Nan::New<Integer>(result));
        return;
      } catch (Platform::Exception ^exception) {
        NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
        return;
      }
    }
      

    static void InkContinuousGetter(Local<String> property, const Nan::PropertyCallbackInfo<v8::Value> &info) {
      HandleScope scope;

      try
      {
        unsigned short result = ::Windows::Devices::Haptics::KnownSimpleHapticsControllerWaveforms::InkContinuous;
        info.GetReturnValue().Set(Nan::New<Integer>(result));
        return;
      } catch (Platform::Exception ^exception) {
        NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
        return;
      }
    }
      

    static void MarkerContinuousGetter(Local<String> property, const Nan::PropertyCallbackInfo<v8::Value> &info) {
      HandleScope scope;

      try
      {
        unsigned short result = ::Windows::Devices::Haptics::KnownSimpleHapticsControllerWaveforms::MarkerContinuous;
        info.GetReturnValue().Set(Nan::New<Integer>(result));
        return;
      } catch (Platform::Exception ^exception) {
        NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
        return;
      }
    }
      

    static void PencilContinuousGetter(Local<String> property, const Nan::PropertyCallbackInfo<v8::Value> &info) {
      HandleScope scope;

      try
      {
        unsigned short result = ::Windows::Devices::Haptics::KnownSimpleHapticsControllerWaveforms::PencilContinuous;
        info.GetReturnValue().Set(Nan::New<Integer>(result));
        return;
      } catch (Platform::Exception ^exception) {
        NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
        return;
      }
    }
      

    static void SuccessGetter(Local<String> property, const Nan::PropertyCallbackInfo<v8::Value> &info) {
      HandleScope scope;

      try
      {
        unsigned short result = ::Windows::Devices::Haptics::KnownSimpleHapticsControllerWaveforms::Success;
        info.GetReturnValue().Set(Nan::New<Integer>(result));
        return;
      } catch (Platform::Exception ^exception) {
        NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
        return;
      }
    }
      

    private:
      ::Windows::Devices::Haptics::KnownSimpleHapticsControllerWaveforms^ _instance;
      static Persistent<FunctionTemplate> s_constructorTemplate;

      friend v8::Local<v8::Value> WrapKnownSimpleHapticsControllerWaveforms(::Windows::Devices::Haptics::KnownSimpleHapticsControllerWaveforms^ wintRtInstance);
      friend ::Windows::Devices::Haptics::KnownSimpleHapticsControllerWaveforms^ UnwrapKnownSimpleHapticsControllerWaveforms(Local<Value> value);
  };

  Persistent<FunctionTemplate> KnownSimpleHapticsControllerWaveforms::s_constructorTemplate;

  v8::Local<v8::Value> WrapKnownSimpleHapticsControllerWaveforms(::Windows::Devices::Haptics::KnownSimpleHapticsControllerWaveforms^ 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>(KnownSimpleHapticsControllerWaveforms::s_constructorTemplate);
    return scope.Escape(Nan::NewInstance(Nan::GetFunction(localRef).ToLocalChecked(),_countof(args), args).ToLocalChecked());
  }

  ::Windows::Devices::Haptics::KnownSimpleHapticsControllerWaveforms^ UnwrapKnownSimpleHapticsControllerWaveforms(Local<Value> value) {
     return KnownSimpleHapticsControllerWaveforms::Unwrap<KnownSimpleHapticsControllerWaveforms>(Nan::To<Object>(value).ToLocalChecked())->_instance;
  }

  void InitKnownSimpleHapticsControllerWaveforms(Local<Object> exports) {
    KnownSimpleHapticsControllerWaveforms::Init(exports);
  }

  class SimpleHapticsController : 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>("SimpleHapticsController").ToLocalChecked());
        localRef->InstanceTemplate()->SetInternalFieldCount(1);


          
            Nan::SetPrototypeMethod(localRef, "stopFeedback", StopFeedback);
            Nan::SetPrototypeMethod(localRef, "sendHapticFeedback", SendHapticFeedback);
            Nan::SetPrototypeMethod(localRef, "sendHapticFeedbackForDuration", SendHapticFeedbackForDuration);
            Nan::SetPrototypeMethod(localRef, "sendHapticFeedbackForPlayCount", SendHapticFeedbackForPlayCount);
          



          
            Nan::SetAccessor(localRef->PrototypeTemplate(), Nan::New<String>("id").ToLocalChecked(), IdGetter);
            Nan::SetAccessor(localRef->PrototypeTemplate(), Nan::New<String>("isIntensitySupported").ToLocalChecked(), IsIntensitySupportedGetter);
            Nan::SetAccessor(localRef->PrototypeTemplate(), Nan::New<String>("isPlayCountSupported").ToLocalChecked(), IsPlayCountSupportedGetter);
            Nan::SetAccessor(localRef->PrototypeTemplate(), Nan::New<String>("isPlayDurationSupported").ToLocalChecked(), IsPlayDurationSupportedGetter);
            Nan::SetAccessor(localRef->PrototypeTemplate(), Nan::New<String>("isReplayPauseIntervalSupported").ToLocalChecked(), IsReplayPauseIntervalSupportedGetter);
            Nan::SetAccessor(localRef->PrototypeTemplate(), Nan::New<String>("supportedFeedback").ToLocalChecked(), SupportedFeedbackGetter);

        Local<Object> constructor = Nan::To<Object>(Nan::GetFunction(localRef).ToLocalChecked()).ToLocalChecked();
        Nan::SetMethod(constructor, "castFrom", CastFrom);



        Nan::Set(exports, Nan::New<String>("SimpleHapticsController").ToLocalChecked(), constructor);
      }

      virtual ::Platform::Object^ GetObjectInstance() const override {
        return _instance;
      }

    private:

      SimpleHapticsController(::Windows::Devices::Haptics::SimpleHapticsController^ 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::Devices::Haptics::SimpleHapticsController^ winRtInstance;


      if (info.Length() == 1 && OpaqueWrapper::IsOpaqueWrapper(info[0]) &&
        NodeRT::Utils::IsWinRtWrapperOf<::Windows::Devices::Haptics::SimpleHapticsController^>(info[0])) {
        try {
          winRtInstance = (::Windows::Devices::Haptics::SimpleHapticsController^) 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());

      SimpleHapticsController *wrapperInstance = new SimpleHapticsController(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::Devices::Haptics::SimpleHapticsController^>(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::Devices::Haptics::SimpleHapticsController^ winRtInstance;
      try {
        winRtInstance = (::Windows::Devices::Haptics::SimpleHapticsController^) NodeRT::Utils::GetObjectInstance(info[0]);
      } catch (Platform::Exception ^exception) {
        NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
        return;
      }

      info.GetReturnValue().Set(WrapSimpleHapticsController(winRtInstance));
    }


    static void StopFeedback(Nan::NAN_METHOD_ARGS_TYPE info) {
      HandleScope scope;

      if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::Devices::Haptics::SimpleHapticsController^>(info.This())) {
        return;
      }

      SimpleHapticsController *wrapper = SimpleHapticsController::Unwrap<SimpleHapticsController>(info.This());

      if (info.Length() == 0)
      {
        try
        {
          wrapper->_instance->StopFeedback();
          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 SendHapticFeedback(Nan::NAN_METHOD_ARGS_TYPE info) {
      HandleScope scope;

      if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::Devices::Haptics::SimpleHapticsController^>(info.This())) {
        return;
      }

      SimpleHapticsController *wrapper = SimpleHapticsController::Unwrap<SimpleHapticsController>(info.This());

      if (info.Length() == 1
        && NodeRT::Utils::IsWinRtWrapperOf<::Windows::Devices::Haptics::SimpleHapticsControllerFeedback^>(info[0]))
      {
        try
        {
          ::Windows::Devices::Haptics::SimpleHapticsControllerFeedback^ arg0 = UnwrapSimpleHapticsControllerFeedback(info[0]);
          
          wrapper->_instance->SendHapticFeedback(arg0);
          return;
        } catch (Platform::Exception ^exception) {
          NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
          return;
        }
      }
      else if (info.Length() == 2
        && NodeRT::Utils::IsWinRtWrapperOf<::Windows::Devices::Haptics::SimpleHapticsControllerFeedback^>(info[0])
        && info[1]->IsNumber())
      {
        try
        {
          ::Windows::Devices::Haptics::SimpleHapticsControllerFeedback^ arg0 = UnwrapSimpleHapticsControllerFeedback(info[0]);
          double arg1 = Nan::To<double>(info[1]).FromMaybe(0.0);
          
          wrapper->_instance->SendHapticFeedback(arg0, arg1);
          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 SendHapticFeedbackForDuration(Nan::NAN_METHOD_ARGS_TYPE info) {
      HandleScope scope;

      if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::Devices::Haptics::SimpleHapticsController^>(info.This())) {
        return;
      }

      SimpleHapticsController *wrapper = SimpleHapticsController::Unwrap<SimpleHapticsController>(info.This());

      if (info.Length() == 3
        && NodeRT::Utils::IsWinRtWrapperOf<::Windows::Devices::Haptics::SimpleHapticsControllerFeedback^>(info[0])
        && info[1]->IsNumber()
        && info[2]->IsNumber())
      {
        try
        {
          ::Windows::Devices::Haptics::SimpleHapticsControllerFeedback^ arg0 = UnwrapSimpleHapticsControllerFeedback(info[0]);
          double arg1 = Nan::To<double>(info[1]).FromMaybe(0.0);
          ::Windows::Foundation::TimeSpan arg2 = NodeRT::Utils::TimeSpanFromMilli(Nan::To<int64_t>(info[2]).FromMaybe(0));
          
          wrapper->_instance->SendHapticFeedbackForDuration(arg0, arg1, arg2);
          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 SendHapticFeedbackForPlayCount(Nan::NAN_METHOD_ARGS_TYPE info) {
      HandleScope scope;

      if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::Devices::Haptics::SimpleHapticsController^>(info.This())) {
        return;
      }

      SimpleHapticsController *wrapper = SimpleHapticsController::Unwrap<SimpleHapticsController>(info.This());

      if (info.Length() == 4
        && NodeRT::Utils::IsWinRtWrapperOf<::Windows::Devices::Haptics::SimpleHapticsControllerFeedback^>(info[0])
        && info[1]->IsNumber()
        && info[2]->IsInt32()
        && info[3]->IsNumber())
      {
        try
        {
          ::Windows::Devices::Haptics::SimpleHapticsControllerFeedback^ arg0 = UnwrapSimpleHapticsControllerFeedback(info[0]);
          double arg1 = Nan::To<double>(info[1]).FromMaybe(0.0);
          int arg2 = static_cast<int>(Nan::To<int32_t>(info[2]).FromMaybe(0));
          ::Windows::Foundation::TimeSpan arg3 = NodeRT::Utils::TimeSpanFromMilli(Nan::To<int64_t>(info[3]).FromMaybe(0));
          
          wrapper->_instance->SendHapticFeedbackForPlayCount(arg0, arg1, arg2, arg3);
          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::Devices::Haptics::SimpleHapticsController^>(info.This())) {
        return;
      }

      SimpleHapticsController *wrapper = SimpleHapticsController::Unwrap<SimpleHapticsController>(info.This());

      try  {
        Platform::String^ result = wrapper->_instance->Id;
        info.GetReturnValue().Set(NodeRT::Utils::NewString(result->Data()));
        return;
      } catch (Platform::Exception ^exception) {
        NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
        return;
      }
    }
      
    static void IsIntensitySupportedGetter(Local<String> property, const Nan::PropertyCallbackInfo<v8::Value> &info) {
      HandleScope scope;

      if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::Devices::Haptics::SimpleHapticsController^>(info.This())) {
        return;
      }

      SimpleHapticsController *wrapper = SimpleHapticsController::Unwrap<SimpleHapticsController>(info.This());

      try  {
        bool result = wrapper->_instance->IsIntensitySupported;
        info.GetReturnValue().Set(Nan::New<Boolean>(result));
        return;
      } catch (Platform::Exception ^exception) {
        NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
        return;
      }
    }
      
    static void IsPlayCountSupportedGetter(Local<String> property, const Nan::PropertyCallbackInfo<v8::Value> &info) {
      HandleScope scope;

      if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::Devices::Haptics::SimpleHapticsController^>(info.This())) {
        return;
      }

      SimpleHapticsController *wrapper = SimpleHapticsController::Unwrap<SimpleHapticsController>(info.This());

      try  {
        bool result = wrapper->_instance->IsPlayCountSupported;
        info.GetReturnValue().Set(Nan::New<Boolean>(result));
        return;
      } catch (Platform::Exception ^exception) {
        NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
        return;
      }
    }
      
    static void IsPlayDurationSupportedGetter(Local<String> property, const Nan::PropertyCallbackInfo<v8::Value> &info) {
      HandleScope scope;

      if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::Devices::Haptics::SimpleHapticsController^>(info.This())) {
        return;
      }

      SimpleHapticsController *wrapper = SimpleHapticsController::Unwrap<SimpleHapticsController>(info.This());

      try  {
        bool result = wrapper->_instance->IsPlayDurationSupported;
        info.GetReturnValue().Set(Nan::New<Boolean>(result));
        return;
      } catch (Platform::Exception ^exception) {
        NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
        return;
      }
    }
      
    static void IsReplayPauseIntervalSupportedGetter(Local<String> property, const Nan::PropertyCallbackInfo<v8::Value> &info) {
      HandleScope scope;

      if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::Devices::Haptics::SimpleHapticsController^>(info.This())) {
        return;
      }

      SimpleHapticsController *wrapper = SimpleHapticsController::Unwrap<SimpleHapticsController>(info.This());

      try  {
        bool result = wrapper->_instance->IsReplayPauseIntervalSupported;
        info.GetReturnValue().Set(Nan::New<Boolean>(result));
        return;
      } catch (Platform::Exception ^exception) {
        NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
        return;
      }
    }
      
    static void SupportedFeedbackGetter(Local<String> property, const Nan::PropertyCallbackInfo<v8::Value> &info) {
      HandleScope scope;

      if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::Devices::Haptics::SimpleHapticsController^>(info.This())) {
        return;
      }

      SimpleHapticsController *wrapper = SimpleHapticsController::Unwrap<SimpleHapticsController>(info.This());

      try  {
        ::Windows::Foundation::Collections::IVectorView<::Windows::Devices::Haptics::SimpleHapticsControllerFeedback^>^ result = wrapper->_instance->SupportedFeedback;
        info.GetReturnValue().Set(NodeRT::Collections::VectorViewWrapper<::Windows::Devices::Haptics::SimpleHapticsControllerFeedback^>::CreateVectorViewWrapper(result, 
            [](::Windows::Devices::Haptics::SimpleHapticsControllerFeedback^ val) -> Local<Value> {
              return WrapSimpleHapticsControllerFeedback(val);
            },
            [](Local<Value> value) -> bool {
              return NodeRT::Utils::IsWinRtWrapperOf<::Windows::Devices::Haptics::SimpleHapticsControllerFeedback^>(value);
            },
            [](Local<Value> value) -> ::Windows::Devices::Haptics::SimpleHapticsControllerFeedback^ {
              return UnwrapSimpleHapticsControllerFeedback(value);
            }
          ));
        return;
      } catch (Platform::Exception ^exception) {
        NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
        return;
      }
    }
      


    private:
      ::Windows::Devices::Haptics::SimpleHapticsController^ _instance;
      static Persistent<FunctionTemplate> s_constructorTemplate;

      friend v8::Local<v8::Value> WrapSimpleHapticsController(::Windows::Devices::Haptics::SimpleHapticsController^ wintRtInstance);
      friend ::Windows::Devices::Haptics::SimpleHapticsController^ UnwrapSimpleHapticsController(Local<Value> value);
  };

  Persistent<FunctionTemplate> SimpleHapticsController::s_constructorTemplate;

  v8::Local<v8::Value> WrapSimpleHapticsController(::Windows::Devices::Haptics::SimpleHapticsController^ 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>(SimpleHapticsController::s_constructorTemplate);
    return scope.Escape(Nan::NewInstance(Nan::GetFunction(localRef).ToLocalChecked(),_countof(args), args).ToLocalChecked());
  }

  ::Windows::Devices::Haptics::SimpleHapticsController^ UnwrapSimpleHapticsController(Local<Value> value) {
     return SimpleHapticsController::Unwrap<SimpleHapticsController>(Nan::To<Object>(value).ToLocalChecked())->_instance;
  }

  void InitSimpleHapticsController(Local<Object> exports) {
    SimpleHapticsController::Init(exports);
  }

  class SimpleHapticsControllerFeedback : 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>("SimpleHapticsControllerFeedback").ToLocalChecked());
        localRef->InstanceTemplate()->SetInternalFieldCount(1);





          
            Nan::SetAccessor(localRef->PrototypeTemplate(), Nan::New<String>("duration").ToLocalChecked(), DurationGetter);
            Nan::SetAccessor(localRef->PrototypeTemplate(), Nan::New<String>("waveform").ToLocalChecked(), WaveformGetter);

        Local<Object> constructor = Nan::To<Object>(Nan::GetFunction(localRef).ToLocalChecked()).ToLocalChecked();
        Nan::SetMethod(constructor, "castFrom", CastFrom);



        Nan::Set(exports, Nan::New<String>("SimpleHapticsControllerFeedback").ToLocalChecked(), constructor);
      }

      virtual ::Platform::Object^ GetObjectInstance() const override {
        return _instance;
      }

    private:

      SimpleHapticsControllerFeedback(::Windows::Devices::Haptics::SimpleHapticsControllerFeedback^ 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::Devices::Haptics::SimpleHapticsControllerFeedback^ winRtInstance;


      if (info.Length() == 1 && OpaqueWrapper::IsOpaqueWrapper(info[0]) &&
        NodeRT::Utils::IsWinRtWrapperOf<::Windows::Devices::Haptics::SimpleHapticsControllerFeedback^>(info[0])) {
        try {
          winRtInstance = (::Windows::Devices::Haptics::SimpleHapticsControllerFeedback^) 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());

      SimpleHapticsControllerFeedback *wrapperInstance = new SimpleHapticsControllerFeedback(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::Devices::Haptics::SimpleHapticsControllerFeedback^>(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::Devices::Haptics::SimpleHapticsControllerFeedback^ winRtInstance;
      try {
        winRtInstance = (::Windows::Devices::Haptics::SimpleHapticsControllerFeedback^) NodeRT::Utils::GetObjectInstance(info[0]);
      } catch (Platform::Exception ^exception) {
        NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
        return;
      }

      info.GetReturnValue().Set(WrapSimpleHapticsControllerFeedback(winRtInstance));
    }





    static void DurationGetter(Local<String> property, const Nan::PropertyCallbackInfo<v8::Value> &info) {
      HandleScope scope;

      if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::Devices::Haptics::SimpleHapticsControllerFeedback^>(info.This())) {
        return;
      }

      SimpleHapticsControllerFeedback *wrapper = SimpleHapticsControllerFeedback::Unwrap<SimpleHapticsControllerFeedback>(info.This());

      try  {
        ::Windows::Foundation::TimeSpan result = wrapper->_instance->Duration;
        info.GetReturnValue().Set(Nan::New<Number>(result.Duration/10000.0));
        return;
      } catch (Platform::Exception ^exception) {
        NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
        return;
      }
    }
      
    static void WaveformGetter(Local<String> property, const Nan::PropertyCallbackInfo<v8::Value> &info) {
      HandleScope scope;

      if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::Devices::Haptics::SimpleHapticsControllerFeedback^>(info.This())) {
        return;
      }

      SimpleHapticsControllerFeedback *wrapper = SimpleHapticsControllerFeedback::Unwrap<SimpleHapticsControllerFeedback>(info.This());

      try  {
        unsigned short result = wrapper->_instance->Waveform;
        info.GetReturnValue().Set(Nan::New<Integer>(result));
        return;
      } catch (Platform::Exception ^exception) {
        NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
        return;
      }
    }
      


    private:
      ::Windows::Devices::Haptics::SimpleHapticsControllerFeedback^ _instance;
      static Persistent<FunctionTemplate> s_constructorTemplate;

      friend v8::Local<v8::Value> WrapSimpleHapticsControllerFeedback(::Windows::Devices::Haptics::SimpleHapticsControllerFeedback^ wintRtInstance);
      friend ::Windows::Devices::Haptics::SimpleHapticsControllerFeedback^ UnwrapSimpleHapticsControllerFeedback(Local<Value> value);
  };

  Persistent<FunctionTemplate> SimpleHapticsControllerFeedback::s_constructorTemplate;

  v8::Local<v8::Value> WrapSimpleHapticsControllerFeedback(::Windows::Devices::Haptics::SimpleHapticsControllerFeedback^ 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>(SimpleHapticsControllerFeedback::s_constructorTemplate);
    return scope.Escape(Nan::NewInstance(Nan::GetFunction(localRef).ToLocalChecked(),_countof(args), args).ToLocalChecked());
  }

  ::Windows::Devices::Haptics::SimpleHapticsControllerFeedback^ UnwrapSimpleHapticsControllerFeedback(Local<Value> value) {
     return SimpleHapticsControllerFeedback::Unwrap<SimpleHapticsControllerFeedback>(Nan::To<Object>(value).ToLocalChecked())->_instance;
  }

  void InitSimpleHapticsControllerFeedback(Local<Object> exports) {
    SimpleHapticsControllerFeedback::Init(exports);
  }

  class VibrationDevice : 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>("VibrationDevice").ToLocalChecked());
        localRef->InstanceTemplate()->SetInternalFieldCount(1);

        Local<Function> func;
        Local<FunctionTemplate> funcTemplate;




          
            Nan::SetAccessor(localRef->PrototypeTemplate(), Nan::New<String>("id").ToLocalChecked(), IdGetter);
            Nan::SetAccessor(localRef->PrototypeTemplate(), Nan::New<String>("simpleHapticsController").ToLocalChecked(), SimpleHapticsControllerGetter);

        Local<Object> constructor = Nan::To<Object>(Nan::GetFunction(localRef).ToLocalChecked()).ToLocalChecked();
        Nan::SetMethod(constructor, "castFrom", CastFrom);

        Nan::SetMethod(constructor, "getDeviceSelector", GetDeviceSelector);
        func = Nan::GetFunction(Nan::New<FunctionTemplate>(RequestAccessAsync)).ToLocalChecked();
        Nan::Set(constructor, Nan::New<String>("requestAccessAsync").ToLocalChecked(), func);
        func = Nan::GetFunction(Nan::New<FunctionTemplate>(FromIdAsync)).ToLocalChecked();
        Nan::Set(constructor, Nan::New<String>("fromIdAsync").ToLocalChecked(), func);
        func = Nan::GetFunction(Nan::New<FunctionTemplate>(GetDefaultAsync)).ToLocalChecked();
        Nan::Set(constructor, Nan::New<String>("getDefaultAsync").ToLocalChecked(), func);
        func = Nan::GetFunction(Nan::New<FunctionTemplate>(FindAllAsync)).ToLocalChecked();
        Nan::Set(constructor, Nan::New<String>("findAllAsync").ToLocalChecked(), func);


        Nan::Set(exports, Nan::New<String>("VibrationDevice").ToLocalChecked(), constructor);
      }

      virtual ::Platform::Object^ GetObjectInstance() const override {
        return _instance;
      }

    private:

      VibrationDevice(::Windows::Devices::Haptics::VibrationDevice^ 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::Devices::Haptics::VibrationDevice^ winRtInstance;


      if (info.Length() == 1 && OpaqueWrapper::IsOpaqueWrapper(info[0]) &&
        NodeRT::Utils::IsWinRtWrapperOf<::Windows::Devices::Haptics::VibrationDevice^>(info[0])) {
        try {
          winRtInstance = (::Windows::Devices::Haptics::VibrationDevice^) 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());

      VibrationDevice *wrapperInstance = new VibrationDevice(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::Devices::Haptics::VibrationDevice^>(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::Devices::Haptics::VibrationDevice^ winRtInstance;
      try {
        winRtInstance = (::Windows::Devices::Haptics::VibrationDevice^) NodeRT::Utils::GetObjectInstance(info[0]);
      } catch (Platform::Exception ^exception) {
        NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
        return;
      }

      info.GetReturnValue().Set(WrapVibrationDevice(winRtInstance));
    }




    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::Devices::Haptics::VibrationAccessStatus>^ op;


      if (info.Length() == 1)
      {
        try
        {
          op = ::Windows::Devices::Haptics::VibrationDevice::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::Devices::Haptics::VibrationAccessStatus> 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 FromIdAsync(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::Devices::Haptics::VibrationDevice^>^ op;


      if (info.Length() == 2
          && info[0]->IsString())
      {
        try
        {
          Platform::String^ arg0 = ref new Platform::String(NodeRT::Utils::StringToWchar(v8::String::Value(v8::Isolate::GetCurrent(), info[0])));
            
          op = ::Windows::Devices::Haptics::VibrationDevice::FromIdAsync(arg0);
        } 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::Devices::Haptics::VibrationDevice^> t)
      {
        try {
          auto result = t.get();
          NodeUtils::Async::RunCallbackOnMain(asyncToken, [result](NodeUtils::InvokeCallbackDelegate invokeCallback) {


            Local<Value> error;
            Local<Value> arg1;
            {
              TryCatch tryCatch;
              arg1 = WrapVibrationDevice(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 GetDefaultAsync(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::Devices::Haptics::VibrationDevice^>^ op;


      if (info.Length() == 1)
      {
        try
        {
          op = ::Windows::Devices::Haptics::VibrationDevice::GetDefaultAsync();
        } 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::Devices::Haptics::VibrationDevice^> t)
      {
        try {
          auto result = t.get();
          NodeUtils::Async::RunCallbackOnMain(asyncToken, [result](NodeUtils::InvokeCallbackDelegate invokeCallback) {


            Local<Value> error;
            Local<Value> arg1;
            {
              TryCatch tryCatch;
              arg1 = WrapVibrationDevice(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 FindAllAsync(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::Foundation::Collections::IVectorView<::Windows::Devices::Haptics::VibrationDevice^>^>^ op;


      if (info.Length() == 1)
      {
        try
        {
          op = ::Windows::Devices::Haptics::VibrationDevice::FindAllAsync();
        } 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::Foundation::Collections::IVectorView<::Windows::Devices::Haptics::VibrationDevice^>^> t)
      {
        try {
          auto result = t.get();
          NodeUtils::Async::RunCallbackOnMain(asyncToken, [result](NodeUtils::InvokeCallbackDelegate invokeCallback) {


            Local<Value> error;
            Local<Value> arg1;
            {
              TryCatch tryCatch;
              arg1 = NodeRT::Collections::VectorViewWrapper<::Windows::Devices::Haptics::VibrationDevice^>::CreateVectorViewWrapper(result, 
            [](::Windows::Devices::Haptics::VibrationDevice^ val) -> Local<Value> {
              return WrapVibrationDevice(val);
            },
            [](Local<Value> value) -> bool {
              return NodeRT::Utils::IsWinRtWrapperOf<::Windows::Devices::Haptics::VibrationDevice^>(value);
            },
            [](Local<Value> value) -> ::Windows::Devices::Haptics::VibrationDevice^ {
              return UnwrapVibrationDevice(value);
            }
          );
              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 GetDeviceSelector(Nan::NAN_METHOD_ARGS_TYPE info) {
      HandleScope scope;

      if (info.Length() == 0)
      {
        try
        {
          Platform::String^ result;
          result = ::Windows::Devices::Haptics::VibrationDevice::GetDeviceSelector();
          info.GetReturnValue().Set(NodeRT::Utils::NewString(result->Data()));
          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::Devices::Haptics::VibrationDevice^>(info.This())) {
        return;
      }

      VibrationDevice *wrapper = VibrationDevice::Unwrap<VibrationDevice>(info.This());

      try  {
        Platform::String^ result = wrapper->_instance->Id;
        info.GetReturnValue().Set(NodeRT::Utils::NewString(result->Data()));
        return;
      } catch (Platform::Exception ^exception) {
        NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
        return;
      }
    }
      
    static void SimpleHapticsControllerGetter(Local<String> property, const Nan::PropertyCallbackInfo<v8::Value> &info) {
      HandleScope scope;

      if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::Devices::Haptics::VibrationDevice^>(info.This())) {
        return;
      }

      VibrationDevice *wrapper = VibrationDevice::Unwrap<VibrationDevice>(info.This());

      try  {
        ::Windows::Devices::Haptics::SimpleHapticsController^ result = wrapper->_instance->SimpleHapticsController;
        info.GetReturnValue().Set(WrapSimpleHapticsController(result));
        return;
      } catch (Platform::Exception ^exception) {
        NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
        return;
      }
    }
      


    private:
      ::Windows::Devices::Haptics::VibrationDevice^ _instance;
      static Persistent<FunctionTemplate> s_constructorTemplate;

      friend v8::Local<v8::Value> WrapVibrationDevice(::Windows::Devices::Haptics::VibrationDevice^ wintRtInstance);
      friend ::Windows::Devices::Haptics::VibrationDevice^ UnwrapVibrationDevice(Local<Value> value);
  };

  Persistent<FunctionTemplate> VibrationDevice::s_constructorTemplate;

  v8::Local<v8::Value> WrapVibrationDevice(::Windows::Devices::Haptics::VibrationDevice^ 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>(VibrationDevice::s_constructorTemplate);
    return scope.Escape(Nan::NewInstance(Nan::GetFunction(localRef).ToLocalChecked(),_countof(args), args).ToLocalChecked());
  }

  ::Windows::Devices::Haptics::VibrationDevice^ UnwrapVibrationDevice(Local<Value> value) {
     return VibrationDevice::Unwrap<VibrationDevice>(Nan::To<Object>(value).ToLocalChecked())->_instance;
  }

  void InitVibrationDevice(Local<Object> exports) {
    VibrationDevice::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::Devices::Haptics::InitVibrationAccessStatusEnum(target);
      NodeRT::Windows::Devices::Haptics::InitKnownSimpleHapticsControllerWaveforms(target);
      NodeRT::Windows::Devices::Haptics::InitSimpleHapticsController(target);
      NodeRT::Windows::Devices::Haptics::InitSimpleHapticsControllerFeedback(target);
      NodeRT::Windows::Devices::Haptics::InitVibrationDevice(target);


  NodeRT::Utils::RegisterNameSpace("Windows.Devices.Haptics", target);
}



NODE_MODULE(binding, init)
