// 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 Bluetooth { namespace Rfcomm { 
  v8::Local<v8::Value> WrapRfcommDeviceService(::Windows::Devices::Bluetooth::Rfcomm::RfcommDeviceService^ wintRtInstance);
  ::Windows::Devices::Bluetooth::Rfcomm::RfcommDeviceService^ UnwrapRfcommDeviceService(Local<Value> value);
  
  v8::Local<v8::Value> WrapRfcommDeviceServicesResult(::Windows::Devices::Bluetooth::Rfcomm::RfcommDeviceServicesResult^ wintRtInstance);
  ::Windows::Devices::Bluetooth::Rfcomm::RfcommDeviceServicesResult^ UnwrapRfcommDeviceServicesResult(Local<Value> value);
  
  v8::Local<v8::Value> WrapRfcommServiceId(::Windows::Devices::Bluetooth::Rfcomm::RfcommServiceId^ wintRtInstance);
  ::Windows::Devices::Bluetooth::Rfcomm::RfcommServiceId^ UnwrapRfcommServiceId(Local<Value> value);
  
  v8::Local<v8::Value> WrapRfcommServiceProvider(::Windows::Devices::Bluetooth::Rfcomm::RfcommServiceProvider^ wintRtInstance);
  ::Windows::Devices::Bluetooth::Rfcomm::RfcommServiceProvider^ UnwrapRfcommServiceProvider(Local<Value> value);
  





  class RfcommDeviceService : 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>("RfcommDeviceService").ToLocalChecked());
        localRef->InstanceTemplate()->SetInternalFieldCount(1);

        Local<Function> func;
        Local<FunctionTemplate> funcTemplate;

          
            Nan::SetPrototypeMethod(localRef, "close", Close);
          

          
            Nan::SetPrototypeMethod(localRef, "getSdpRawAttributesAsync", GetSdpRawAttributesAsync);
            Nan::SetPrototypeMethod(localRef, "requestAccessAsync", RequestAccessAsync);
          


          
            Nan::SetAccessor(localRef->PrototypeTemplate(), Nan::New<String>("connectionHostName").ToLocalChecked(), ConnectionHostNameGetter);
            Nan::SetAccessor(localRef->PrototypeTemplate(), Nan::New<String>("connectionServiceName").ToLocalChecked(), ConnectionServiceNameGetter);
            Nan::SetAccessor(localRef->PrototypeTemplate(), Nan::New<String>("maxProtectionLevel").ToLocalChecked(), MaxProtectionLevelGetter);
            Nan::SetAccessor(localRef->PrototypeTemplate(), Nan::New<String>("protectionLevel").ToLocalChecked(), ProtectionLevelGetter);
            Nan::SetAccessor(localRef->PrototypeTemplate(), Nan::New<String>("serviceId").ToLocalChecked(), ServiceIdGetter);
            Nan::SetAccessor(localRef->PrototypeTemplate(), Nan::New<String>("device").ToLocalChecked(), DeviceGetter);
            Nan::SetAccessor(localRef->PrototypeTemplate(), Nan::New<String>("deviceAccessInformation").ToLocalChecked(), DeviceAccessInformationGetter);

        Local<Object> constructor = Nan::To<Object>(Nan::GetFunction(localRef).ToLocalChecked()).ToLocalChecked();
        Nan::SetMethod(constructor, "castFrom", CastFrom);

        Nan::SetMethod(constructor, "getDeviceSelectorForBluetoothDevice", GetDeviceSelectorForBluetoothDevice);
        Nan::SetMethod(constructor, "getDeviceSelectorForBluetoothDeviceAndServiceId", GetDeviceSelectorForBluetoothDeviceAndServiceId);
        Nan::SetMethod(constructor, "getDeviceSelector", GetDeviceSelector);
        func = Nan::GetFunction(Nan::New<FunctionTemplate>(FromIdAsync)).ToLocalChecked();
        Nan::Set(constructor, Nan::New<String>("fromIdAsync").ToLocalChecked(), func);


        Nan::Set(exports, Nan::New<String>("RfcommDeviceService").ToLocalChecked(), constructor);
      }

      virtual ::Platform::Object^ GetObjectInstance() const override {
        return _instance;
      }

    private:

      RfcommDeviceService(::Windows::Devices::Bluetooth::Rfcomm::RfcommDeviceService^ 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::Bluetooth::Rfcomm::RfcommDeviceService^ winRtInstance;


      if (info.Length() == 1 && OpaqueWrapper::IsOpaqueWrapper(info[0]) &&
        NodeRT::Utils::IsWinRtWrapperOf<::Windows::Devices::Bluetooth::Rfcomm::RfcommDeviceService^>(info[0])) {
        try {
          winRtInstance = (::Windows::Devices::Bluetooth::Rfcomm::RfcommDeviceService^) 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());

      RfcommDeviceService *wrapperInstance = new RfcommDeviceService(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::Bluetooth::Rfcomm::RfcommDeviceService^>(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::Bluetooth::Rfcomm::RfcommDeviceService^ winRtInstance;
      try {
        winRtInstance = (::Windows::Devices::Bluetooth::Rfcomm::RfcommDeviceService^) NodeRT::Utils::GetObjectInstance(info[0]);
      } catch (Platform::Exception ^exception) {
        NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
        return;
      }

      info.GetReturnValue().Set(WrapRfcommDeviceService(winRtInstance));
    }

    static void GetSdpRawAttributesAsync(Nan::NAN_METHOD_ARGS_TYPE info) {
      HandleScope scope;

      if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::Devices::Bluetooth::Rfcomm::RfcommDeviceService^>(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;
      }

      RfcommDeviceService *wrapper = RfcommDeviceService::Unwrap<RfcommDeviceService>(info.This());

      ::Windows::Foundation::IAsyncOperation<::Windows::Foundation::Collections::IMapView<unsigned int, ::Windows::Storage::Streams::IBuffer^>^>^ op;


      if (info.Length() == 1)
      {
        try
        {
          op = wrapper->_instance->GetSdpRawAttributesAsync();
        }
        catch (Platform::Exception ^exception)
        {
          NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
          return;
        }
      }
      else if (info.Length() == 2
        && info[0]->IsInt32())
      {
        try
        {
          ::Windows::Devices::Bluetooth::BluetoothCacheMode arg0 = static_cast<::Windows::Devices::Bluetooth::BluetoothCacheMode>(Nan::To<int32_t>(info[0]).FromMaybe(0));
          
          op = wrapper->_instance->GetSdpRawAttributesAsync(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::Foundation::Collections::IMapView<unsigned int, ::Windows::Storage::Streams::IBuffer^>^> 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::MapViewWrapper<unsigned int,::Windows::Storage::Streams::IBuffer^>::CreateMapViewWrapper(result, 
            [](unsigned int val) -> Local<Value> {
              return Nan::New<Integer>(val);
            },
            [](Local<Value> value) -> bool {
              return value->IsUint32();
            },
            [](Local<Value> value) -> unsigned int {
              return static_cast<unsigned int>(Nan::To<uint32_t>(value).FromMaybe(0));
            },
            [](::Windows::Storage::Streams::IBuffer^ val) -> Local<Value> {
              return NodeRT::Utils::CreateExternalWinRTObject("Windows.Storage.Streams", "IBuffer", val);
            }
          );
              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 RequestAccessAsync(Nan::NAN_METHOD_ARGS_TYPE info) {
      HandleScope scope;

      if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::Devices::Bluetooth::Rfcomm::RfcommDeviceService^>(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;
      }

      RfcommDeviceService *wrapper = RfcommDeviceService::Unwrap<RfcommDeviceService>(info.This());

      ::Windows::Foundation::IAsyncOperation<::Windows::Devices::Enumeration::DeviceAccessStatus>^ op;


      if (info.Length() == 1)
      {
        try
        {
          op = wrapper->_instance->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::Enumeration::DeviceAccessStatus> 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 Close(Nan::NAN_METHOD_ARGS_TYPE info) {
      HandleScope scope;

      if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::Devices::Bluetooth::Rfcomm::RfcommDeviceService^>(info.This())) {
        return;
      }

      RfcommDeviceService *wrapper = RfcommDeviceService::Unwrap<RfcommDeviceService>(info.This());

      if (info.Length() == 0) {
        try {
          delete wrapper->_instance;
          wrapper->_instance = nullptr;
          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 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::Bluetooth::Rfcomm::RfcommDeviceService^>^ 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::Bluetooth::Rfcomm::RfcommDeviceService::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::Bluetooth::Rfcomm::RfcommDeviceService^> t)
      {
        try {
          auto result = t.get();
          NodeUtils::Async::RunCallbackOnMain(asyncToken, [result](NodeUtils::InvokeCallbackDelegate invokeCallback) {


            Local<Value> error;
            Local<Value> arg1;
            {
              TryCatch tryCatch;
              arg1 = WrapRfcommDeviceService(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 GetDeviceSelectorForBluetoothDevice(Nan::NAN_METHOD_ARGS_TYPE info) {
      HandleScope scope;

      if (info.Length() == 1
        && NodeRT::Utils::IsWinRtWrapperOf<::Windows::Devices::Bluetooth::BluetoothDevice^>(info[0]))
      {
        try
        {
          ::Windows::Devices::Bluetooth::BluetoothDevice^ arg0 = dynamic_cast<::Windows::Devices::Bluetooth::BluetoothDevice^>(NodeRT::Utils::GetObjectInstance(info[0]));
          
          Platform::String^ result;
          result = ::Windows::Devices::Bluetooth::Rfcomm::RfcommDeviceService::GetDeviceSelectorForBluetoothDevice(arg0);
          info.GetReturnValue().Set(NodeRT::Utils::NewString(result->Data()));
          return;
        }
        catch (Platform::Exception ^exception)
        {
          NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
          return;
        }
      }
      else if (info.Length() == 2
        && NodeRT::Utils::IsWinRtWrapperOf<::Windows::Devices::Bluetooth::BluetoothDevice^>(info[0])
        && info[1]->IsInt32())
      {
        try
        {
          ::Windows::Devices::Bluetooth::BluetoothDevice^ arg0 = dynamic_cast<::Windows::Devices::Bluetooth::BluetoothDevice^>(NodeRT::Utils::GetObjectInstance(info[0]));
          ::Windows::Devices::Bluetooth::BluetoothCacheMode arg1 = static_cast<::Windows::Devices::Bluetooth::BluetoothCacheMode>(Nan::To<int32_t>(info[1]).FromMaybe(0));
          
          Platform::String^ result;
          result = ::Windows::Devices::Bluetooth::Rfcomm::RfcommDeviceService::GetDeviceSelectorForBluetoothDevice(arg0, arg1);
          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 GetDeviceSelectorForBluetoothDeviceAndServiceId(Nan::NAN_METHOD_ARGS_TYPE info) {
      HandleScope scope;

      if (info.Length() == 2
        && NodeRT::Utils::IsWinRtWrapperOf<::Windows::Devices::Bluetooth::BluetoothDevice^>(info[0])
        && NodeRT::Utils::IsWinRtWrapperOf<::Windows::Devices::Bluetooth::Rfcomm::RfcommServiceId^>(info[1]))
      {
        try
        {
          ::Windows::Devices::Bluetooth::BluetoothDevice^ arg0 = dynamic_cast<::Windows::Devices::Bluetooth::BluetoothDevice^>(NodeRT::Utils::GetObjectInstance(info[0]));
          ::Windows::Devices::Bluetooth::Rfcomm::RfcommServiceId^ arg1 = UnwrapRfcommServiceId(info[1]);
          
          Platform::String^ result;
          result = ::Windows::Devices::Bluetooth::Rfcomm::RfcommDeviceService::GetDeviceSelectorForBluetoothDeviceAndServiceId(arg0, arg1);
          info.GetReturnValue().Set(NodeRT::Utils::NewString(result->Data()));
          return;
        }
        catch (Platform::Exception ^exception)
        {
          NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
          return;
        }
      }
      else if (info.Length() == 3
        && NodeRT::Utils::IsWinRtWrapperOf<::Windows::Devices::Bluetooth::BluetoothDevice^>(info[0])
        && NodeRT::Utils::IsWinRtWrapperOf<::Windows::Devices::Bluetooth::Rfcomm::RfcommServiceId^>(info[1])
        && info[2]->IsInt32())
      {
        try
        {
          ::Windows::Devices::Bluetooth::BluetoothDevice^ arg0 = dynamic_cast<::Windows::Devices::Bluetooth::BluetoothDevice^>(NodeRT::Utils::GetObjectInstance(info[0]));
          ::Windows::Devices::Bluetooth::Rfcomm::RfcommServiceId^ arg1 = UnwrapRfcommServiceId(info[1]);
          ::Windows::Devices::Bluetooth::BluetoothCacheMode arg2 = static_cast<::Windows::Devices::Bluetooth::BluetoothCacheMode>(Nan::To<int32_t>(info[2]).FromMaybe(0));
          
          Platform::String^ result;
          result = ::Windows::Devices::Bluetooth::Rfcomm::RfcommDeviceService::GetDeviceSelectorForBluetoothDeviceAndServiceId(arg0, arg1, arg2);
          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 GetDeviceSelector(Nan::NAN_METHOD_ARGS_TYPE info) {
      HandleScope scope;

      if (info.Length() == 1
        && NodeRT::Utils::IsWinRtWrapperOf<::Windows::Devices::Bluetooth::Rfcomm::RfcommServiceId^>(info[0]))
      {
        try
        {
          ::Windows::Devices::Bluetooth::Rfcomm::RfcommServiceId^ arg0 = UnwrapRfcommServiceId(info[0]);
          
          Platform::String^ result;
          result = ::Windows::Devices::Bluetooth::Rfcomm::RfcommDeviceService::GetDeviceSelector(arg0);
          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 ConnectionHostNameGetter(Local<String> property, const Nan::PropertyCallbackInfo<v8::Value> &info) {
      HandleScope scope;

      if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::Devices::Bluetooth::Rfcomm::RfcommDeviceService^>(info.This())) {
        return;
      }

      RfcommDeviceService *wrapper = RfcommDeviceService::Unwrap<RfcommDeviceService>(info.This());

      try  {
        ::Windows::Networking::HostName^ result = wrapper->_instance->ConnectionHostName;
        info.GetReturnValue().Set(NodeRT::Utils::CreateExternalWinRTObject("Windows.Networking", "HostName", result));
        return;
      } catch (Platform::Exception ^exception) {
        NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
        return;
      }
    }
      
    static void ConnectionServiceNameGetter(Local<String> property, const Nan::PropertyCallbackInfo<v8::Value> &info) {
      HandleScope scope;

      if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::Devices::Bluetooth::Rfcomm::RfcommDeviceService^>(info.This())) {
        return;
      }

      RfcommDeviceService *wrapper = RfcommDeviceService::Unwrap<RfcommDeviceService>(info.This());

      try  {
        Platform::String^ result = wrapper->_instance->ConnectionServiceName;
        info.GetReturnValue().Set(NodeRT::Utils::NewString(result->Data()));
        return;
      } catch (Platform::Exception ^exception) {
        NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
        return;
      }
    }
      
    static void MaxProtectionLevelGetter(Local<String> property, const Nan::PropertyCallbackInfo<v8::Value> &info) {
      HandleScope scope;

      if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::Devices::Bluetooth::Rfcomm::RfcommDeviceService^>(info.This())) {
        return;
      }

      RfcommDeviceService *wrapper = RfcommDeviceService::Unwrap<RfcommDeviceService>(info.This());

      try  {
        ::Windows::Networking::Sockets::SocketProtectionLevel result = wrapper->_instance->MaxProtectionLevel;
        info.GetReturnValue().Set(Nan::New<Integer>(static_cast<int>(result)));
        return;
      } catch (Platform::Exception ^exception) {
        NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
        return;
      }
    }
      
    static void ProtectionLevelGetter(Local<String> property, const Nan::PropertyCallbackInfo<v8::Value> &info) {
      HandleScope scope;

      if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::Devices::Bluetooth::Rfcomm::RfcommDeviceService^>(info.This())) {
        return;
      }

      RfcommDeviceService *wrapper = RfcommDeviceService::Unwrap<RfcommDeviceService>(info.This());

      try  {
        ::Windows::Networking::Sockets::SocketProtectionLevel result = wrapper->_instance->ProtectionLevel;
        info.GetReturnValue().Set(Nan::New<Integer>(static_cast<int>(result)));
        return;
      } catch (Platform::Exception ^exception) {
        NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
        return;
      }
    }
      
    static void ServiceIdGetter(Local<String> property, const Nan::PropertyCallbackInfo<v8::Value> &info) {
      HandleScope scope;

      if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::Devices::Bluetooth::Rfcomm::RfcommDeviceService^>(info.This())) {
        return;
      }

      RfcommDeviceService *wrapper = RfcommDeviceService::Unwrap<RfcommDeviceService>(info.This());

      try  {
        ::Windows::Devices::Bluetooth::Rfcomm::RfcommServiceId^ result = wrapper->_instance->ServiceId;
        info.GetReturnValue().Set(WrapRfcommServiceId(result));
        return;
      } catch (Platform::Exception ^exception) {
        NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
        return;
      }
    }
      
    static void DeviceGetter(Local<String> property, const Nan::PropertyCallbackInfo<v8::Value> &info) {
      HandleScope scope;

      if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::Devices::Bluetooth::Rfcomm::RfcommDeviceService^>(info.This())) {
        return;
      }

      RfcommDeviceService *wrapper = RfcommDeviceService::Unwrap<RfcommDeviceService>(info.This());

      try  {
        ::Windows::Devices::Bluetooth::BluetoothDevice^ result = wrapper->_instance->Device;
        info.GetReturnValue().Set(NodeRT::Utils::CreateExternalWinRTObject("Windows.Devices.Bluetooth", "BluetoothDevice", result));
        return;
      } catch (Platform::Exception ^exception) {
        NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
        return;
      }
    }
      
    static void DeviceAccessInformationGetter(Local<String> property, const Nan::PropertyCallbackInfo<v8::Value> &info) {
      HandleScope scope;

      if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::Devices::Bluetooth::Rfcomm::RfcommDeviceService^>(info.This())) {
        return;
      }

      RfcommDeviceService *wrapper = RfcommDeviceService::Unwrap<RfcommDeviceService>(info.This());

      try  {
        ::Windows::Devices::Enumeration::DeviceAccessInformation^ result = wrapper->_instance->DeviceAccessInformation;
        info.GetReturnValue().Set(NodeRT::Utils::CreateExternalWinRTObject("Windows.Devices.Enumeration", "DeviceAccessInformation", result));
        return;
      } catch (Platform::Exception ^exception) {
        NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
        return;
      }
    }
      


    private:
      ::Windows::Devices::Bluetooth::Rfcomm::RfcommDeviceService^ _instance;
      static Persistent<FunctionTemplate> s_constructorTemplate;

      friend v8::Local<v8::Value> WrapRfcommDeviceService(::Windows::Devices::Bluetooth::Rfcomm::RfcommDeviceService^ wintRtInstance);
      friend ::Windows::Devices::Bluetooth::Rfcomm::RfcommDeviceService^ UnwrapRfcommDeviceService(Local<Value> value);
  };

  Persistent<FunctionTemplate> RfcommDeviceService::s_constructorTemplate;

  v8::Local<v8::Value> WrapRfcommDeviceService(::Windows::Devices::Bluetooth::Rfcomm::RfcommDeviceService^ 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>(RfcommDeviceService::s_constructorTemplate);
    return scope.Escape(Nan::NewInstance(Nan::GetFunction(localRef).ToLocalChecked(),_countof(args), args).ToLocalChecked());
  }

  ::Windows::Devices::Bluetooth::Rfcomm::RfcommDeviceService^ UnwrapRfcommDeviceService(Local<Value> value) {
     return RfcommDeviceService::Unwrap<RfcommDeviceService>(Nan::To<Object>(value).ToLocalChecked())->_instance;
  }

  void InitRfcommDeviceService(Local<Object> exports) {
    RfcommDeviceService::Init(exports);
  }

  class RfcommDeviceServicesResult : 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>("RfcommDeviceServicesResult").ToLocalChecked());
        localRef->InstanceTemplate()->SetInternalFieldCount(1);





          
            Nan::SetAccessor(localRef->PrototypeTemplate(), Nan::New<String>("error").ToLocalChecked(), ErrorGetter);
            Nan::SetAccessor(localRef->PrototypeTemplate(), Nan::New<String>("services").ToLocalChecked(), ServicesGetter);

        Local<Object> constructor = Nan::To<Object>(Nan::GetFunction(localRef).ToLocalChecked()).ToLocalChecked();
        Nan::SetMethod(constructor, "castFrom", CastFrom);



        Nan::Set(exports, Nan::New<String>("RfcommDeviceServicesResult").ToLocalChecked(), constructor);
      }

      virtual ::Platform::Object^ GetObjectInstance() const override {
        return _instance;
      }

    private:

      RfcommDeviceServicesResult(::Windows::Devices::Bluetooth::Rfcomm::RfcommDeviceServicesResult^ 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::Bluetooth::Rfcomm::RfcommDeviceServicesResult^ winRtInstance;


      if (info.Length() == 1 && OpaqueWrapper::IsOpaqueWrapper(info[0]) &&
        NodeRT::Utils::IsWinRtWrapperOf<::Windows::Devices::Bluetooth::Rfcomm::RfcommDeviceServicesResult^>(info[0])) {
        try {
          winRtInstance = (::Windows::Devices::Bluetooth::Rfcomm::RfcommDeviceServicesResult^) 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());

      RfcommDeviceServicesResult *wrapperInstance = new RfcommDeviceServicesResult(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::Bluetooth::Rfcomm::RfcommDeviceServicesResult^>(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::Bluetooth::Rfcomm::RfcommDeviceServicesResult^ winRtInstance;
      try {
        winRtInstance = (::Windows::Devices::Bluetooth::Rfcomm::RfcommDeviceServicesResult^) NodeRT::Utils::GetObjectInstance(info[0]);
      } catch (Platform::Exception ^exception) {
        NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
        return;
      }

      info.GetReturnValue().Set(WrapRfcommDeviceServicesResult(winRtInstance));
    }





    static void ErrorGetter(Local<String> property, const Nan::PropertyCallbackInfo<v8::Value> &info) {
      HandleScope scope;

      if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::Devices::Bluetooth::Rfcomm::RfcommDeviceServicesResult^>(info.This())) {
        return;
      }

      RfcommDeviceServicesResult *wrapper = RfcommDeviceServicesResult::Unwrap<RfcommDeviceServicesResult>(info.This());

      try  {
        ::Windows::Devices::Bluetooth::BluetoothError result = wrapper->_instance->Error;
        info.GetReturnValue().Set(Nan::New<Integer>(static_cast<int>(result)));
        return;
      } catch (Platform::Exception ^exception) {
        NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
        return;
      }
    }
      
    static void ServicesGetter(Local<String> property, const Nan::PropertyCallbackInfo<v8::Value> &info) {
      HandleScope scope;

      if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::Devices::Bluetooth::Rfcomm::RfcommDeviceServicesResult^>(info.This())) {
        return;
      }

      RfcommDeviceServicesResult *wrapper = RfcommDeviceServicesResult::Unwrap<RfcommDeviceServicesResult>(info.This());

      try  {
        ::Windows::Foundation::Collections::IVectorView<::Windows::Devices::Bluetooth::Rfcomm::RfcommDeviceService^>^ result = wrapper->_instance->Services;
        info.GetReturnValue().Set(NodeRT::Collections::VectorViewWrapper<::Windows::Devices::Bluetooth::Rfcomm::RfcommDeviceService^>::CreateVectorViewWrapper(result, 
            [](::Windows::Devices::Bluetooth::Rfcomm::RfcommDeviceService^ val) -> Local<Value> {
              return WrapRfcommDeviceService(val);
            },
            [](Local<Value> value) -> bool {
              return NodeRT::Utils::IsWinRtWrapperOf<::Windows::Devices::Bluetooth::Rfcomm::RfcommDeviceService^>(value);
            },
            [](Local<Value> value) -> ::Windows::Devices::Bluetooth::Rfcomm::RfcommDeviceService^ {
              return UnwrapRfcommDeviceService(value);
            }
          ));
        return;
      } catch (Platform::Exception ^exception) {
        NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
        return;
      }
    }
      


    private:
      ::Windows::Devices::Bluetooth::Rfcomm::RfcommDeviceServicesResult^ _instance;
      static Persistent<FunctionTemplate> s_constructorTemplate;

      friend v8::Local<v8::Value> WrapRfcommDeviceServicesResult(::Windows::Devices::Bluetooth::Rfcomm::RfcommDeviceServicesResult^ wintRtInstance);
      friend ::Windows::Devices::Bluetooth::Rfcomm::RfcommDeviceServicesResult^ UnwrapRfcommDeviceServicesResult(Local<Value> value);
  };

  Persistent<FunctionTemplate> RfcommDeviceServicesResult::s_constructorTemplate;

  v8::Local<v8::Value> WrapRfcommDeviceServicesResult(::Windows::Devices::Bluetooth::Rfcomm::RfcommDeviceServicesResult^ 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>(RfcommDeviceServicesResult::s_constructorTemplate);
    return scope.Escape(Nan::NewInstance(Nan::GetFunction(localRef).ToLocalChecked(),_countof(args), args).ToLocalChecked());
  }

  ::Windows::Devices::Bluetooth::Rfcomm::RfcommDeviceServicesResult^ UnwrapRfcommDeviceServicesResult(Local<Value> value) {
     return RfcommDeviceServicesResult::Unwrap<RfcommDeviceServicesResult>(Nan::To<Object>(value).ToLocalChecked())->_instance;
  }

  void InitRfcommDeviceServicesResult(Local<Object> exports) {
    RfcommDeviceServicesResult::Init(exports);
  }

  class RfcommServiceId : 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>("RfcommServiceId").ToLocalChecked());
        localRef->InstanceTemplate()->SetInternalFieldCount(1);


          
            Nan::SetPrototypeMethod(localRef, "asShortId", AsShortId);
            Nan::SetPrototypeMethod(localRef, "asString", AsString);
          



          
            Nan::SetAccessor(localRef->PrototypeTemplate(), Nan::New<String>("uuid").ToLocalChecked(), UuidGetter);

        Local<Object> constructor = Nan::To<Object>(Nan::GetFunction(localRef).ToLocalChecked()).ToLocalChecked();
        Nan::SetMethod(constructor, "castFrom", CastFrom);

        Nan::SetMethod(constructor, "fromUuid", FromUuid);
        Nan::SetMethod(constructor, "fromShortId", FromShortId);
        Nan::SetAccessor(constructor, Nan::New<String>("genericFileTransfer").ToLocalChecked(), GenericFileTransferGetter);
        Nan::SetAccessor(constructor, Nan::New<String>("obexFileTransfer").ToLocalChecked(), ObexFileTransferGetter);
        Nan::SetAccessor(constructor, Nan::New<String>("obexObjectPush").ToLocalChecked(), ObexObjectPushGetter);
        Nan::SetAccessor(constructor, Nan::New<String>("phoneBookAccessPce").ToLocalChecked(), PhoneBookAccessPceGetter);
        Nan::SetAccessor(constructor, Nan::New<String>("phoneBookAccessPse").ToLocalChecked(), PhoneBookAccessPseGetter);
        Nan::SetAccessor(constructor, Nan::New<String>("serialPort").ToLocalChecked(), SerialPortGetter);


        Nan::Set(exports, Nan::New<String>("RfcommServiceId").ToLocalChecked(), constructor);
      }

      virtual ::Platform::Object^ GetObjectInstance() const override {
        return _instance;
      }

    private:

      RfcommServiceId(::Windows::Devices::Bluetooth::Rfcomm::RfcommServiceId^ 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::Bluetooth::Rfcomm::RfcommServiceId^ winRtInstance;


      if (info.Length() == 1 && OpaqueWrapper::IsOpaqueWrapper(info[0]) &&
        NodeRT::Utils::IsWinRtWrapperOf<::Windows::Devices::Bluetooth::Rfcomm::RfcommServiceId^>(info[0])) {
        try {
          winRtInstance = (::Windows::Devices::Bluetooth::Rfcomm::RfcommServiceId^) 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());

      RfcommServiceId *wrapperInstance = new RfcommServiceId(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::Bluetooth::Rfcomm::RfcommServiceId^>(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::Bluetooth::Rfcomm::RfcommServiceId^ winRtInstance;
      try {
        winRtInstance = (::Windows::Devices::Bluetooth::Rfcomm::RfcommServiceId^) NodeRT::Utils::GetObjectInstance(info[0]);
      } catch (Platform::Exception ^exception) {
        NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
        return;
      }

      info.GetReturnValue().Set(WrapRfcommServiceId(winRtInstance));
    }


    static void AsShortId(Nan::NAN_METHOD_ARGS_TYPE info) {
      HandleScope scope;

      if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::Devices::Bluetooth::Rfcomm::RfcommServiceId^>(info.This())) {
        return;
      }

      RfcommServiceId *wrapper = RfcommServiceId::Unwrap<RfcommServiceId>(info.This());

      if (info.Length() == 0)
      {
        try
        {
          unsigned int result;
          result = wrapper->_instance->AsShortId();
          info.GetReturnValue().Set(Nan::New<Integer>(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 AsString(Nan::NAN_METHOD_ARGS_TYPE info) {
      HandleScope scope;

      if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::Devices::Bluetooth::Rfcomm::RfcommServiceId^>(info.This())) {
        return;
      }

      RfcommServiceId *wrapper = RfcommServiceId::Unwrap<RfcommServiceId>(info.This());

      if (info.Length() == 0)
      {
        try
        {
          Platform::String^ result;
          result = wrapper->_instance->AsString();
          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 FromUuid(Nan::NAN_METHOD_ARGS_TYPE info) {
      HandleScope scope;

      if (info.Length() == 1
        && NodeRT::Utils::IsGuid(info[0]))
      {
        try
        {
          ::Platform::Guid arg0 = NodeRT::Utils::GuidFromJs(info[0]);
          
          ::Windows::Devices::Bluetooth::Rfcomm::RfcommServiceId^ result;
          result = ::Windows::Devices::Bluetooth::Rfcomm::RfcommServiceId::FromUuid(arg0);
          info.GetReturnValue().Set(WrapRfcommServiceId(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 FromShortId(Nan::NAN_METHOD_ARGS_TYPE info) {
      HandleScope scope;

      if (info.Length() == 1
        && info[0]->IsUint32())
      {
        try
        {
          unsigned int arg0 = static_cast<unsigned int>(Nan::To<uint32_t>(info[0]).FromMaybe(0));
          
          ::Windows::Devices::Bluetooth::Rfcomm::RfcommServiceId^ result;
          result = ::Windows::Devices::Bluetooth::Rfcomm::RfcommServiceId::FromShortId(arg0);
          info.GetReturnValue().Set(WrapRfcommServiceId(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 UuidGetter(Local<String> property, const Nan::PropertyCallbackInfo<v8::Value> &info) {
      HandleScope scope;

      if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::Devices::Bluetooth::Rfcomm::RfcommServiceId^>(info.This())) {
        return;
      }

      RfcommServiceId *wrapper = RfcommServiceId::Unwrap<RfcommServiceId>(info.This());

      try  {
        ::Platform::Guid result = wrapper->_instance->Uuid;
        info.GetReturnValue().Set(NodeRT::Utils::GuidToJs(result));
        return;
      } catch (Platform::Exception ^exception) {
        NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
        return;
      }
    }
      


    static void GenericFileTransferGetter(Local<String> property, const Nan::PropertyCallbackInfo<v8::Value> &info) {
      HandleScope scope;

      try
      {
        ::Windows::Devices::Bluetooth::Rfcomm::RfcommServiceId^ result = ::Windows::Devices::Bluetooth::Rfcomm::RfcommServiceId::GenericFileTransfer;
        info.GetReturnValue().Set(WrapRfcommServiceId(result));
        return;
      } catch (Platform::Exception ^exception) {
        NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
        return;
      }
    }
      

    static void ObexFileTransferGetter(Local<String> property, const Nan::PropertyCallbackInfo<v8::Value> &info) {
      HandleScope scope;

      try
      {
        ::Windows::Devices::Bluetooth::Rfcomm::RfcommServiceId^ result = ::Windows::Devices::Bluetooth::Rfcomm::RfcommServiceId::ObexFileTransfer;
        info.GetReturnValue().Set(WrapRfcommServiceId(result));
        return;
      } catch (Platform::Exception ^exception) {
        NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
        return;
      }
    }
      

    static void ObexObjectPushGetter(Local<String> property, const Nan::PropertyCallbackInfo<v8::Value> &info) {
      HandleScope scope;

      try
      {
        ::Windows::Devices::Bluetooth::Rfcomm::RfcommServiceId^ result = ::Windows::Devices::Bluetooth::Rfcomm::RfcommServiceId::ObexObjectPush;
        info.GetReturnValue().Set(WrapRfcommServiceId(result));
        return;
      } catch (Platform::Exception ^exception) {
        NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
        return;
      }
    }
      

    static void PhoneBookAccessPceGetter(Local<String> property, const Nan::PropertyCallbackInfo<v8::Value> &info) {
      HandleScope scope;

      try
      {
        ::Windows::Devices::Bluetooth::Rfcomm::RfcommServiceId^ result = ::Windows::Devices::Bluetooth::Rfcomm::RfcommServiceId::PhoneBookAccessPce;
        info.GetReturnValue().Set(WrapRfcommServiceId(result));
        return;
      } catch (Platform::Exception ^exception) {
        NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
        return;
      }
    }
      

    static void PhoneBookAccessPseGetter(Local<String> property, const Nan::PropertyCallbackInfo<v8::Value> &info) {
      HandleScope scope;

      try
      {
        ::Windows::Devices::Bluetooth::Rfcomm::RfcommServiceId^ result = ::Windows::Devices::Bluetooth::Rfcomm::RfcommServiceId::PhoneBookAccessPse;
        info.GetReturnValue().Set(WrapRfcommServiceId(result));
        return;
      } catch (Platform::Exception ^exception) {
        NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
        return;
      }
    }
      

    static void SerialPortGetter(Local<String> property, const Nan::PropertyCallbackInfo<v8::Value> &info) {
      HandleScope scope;

      try
      {
        ::Windows::Devices::Bluetooth::Rfcomm::RfcommServiceId^ result = ::Windows::Devices::Bluetooth::Rfcomm::RfcommServiceId::SerialPort;
        info.GetReturnValue().Set(WrapRfcommServiceId(result));
        return;
      } catch (Platform::Exception ^exception) {
        NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
        return;
      }
    }
      

    private:
      ::Windows::Devices::Bluetooth::Rfcomm::RfcommServiceId^ _instance;
      static Persistent<FunctionTemplate> s_constructorTemplate;

      friend v8::Local<v8::Value> WrapRfcommServiceId(::Windows::Devices::Bluetooth::Rfcomm::RfcommServiceId^ wintRtInstance);
      friend ::Windows::Devices::Bluetooth::Rfcomm::RfcommServiceId^ UnwrapRfcommServiceId(Local<Value> value);
  };

  Persistent<FunctionTemplate> RfcommServiceId::s_constructorTemplate;

  v8::Local<v8::Value> WrapRfcommServiceId(::Windows::Devices::Bluetooth::Rfcomm::RfcommServiceId^ 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>(RfcommServiceId::s_constructorTemplate);
    return scope.Escape(Nan::NewInstance(Nan::GetFunction(localRef).ToLocalChecked(),_countof(args), args).ToLocalChecked());
  }

  ::Windows::Devices::Bluetooth::Rfcomm::RfcommServiceId^ UnwrapRfcommServiceId(Local<Value> value) {
     return RfcommServiceId::Unwrap<RfcommServiceId>(Nan::To<Object>(value).ToLocalChecked())->_instance;
  }

  void InitRfcommServiceId(Local<Object> exports) {
    RfcommServiceId::Init(exports);
  }

  class RfcommServiceProvider : 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>("RfcommServiceProvider").ToLocalChecked());
        localRef->InstanceTemplate()->SetInternalFieldCount(1);

        Local<Function> func;
        Local<FunctionTemplate> funcTemplate;

          
            Nan::SetPrototypeMethod(localRef, "startAdvertising", StartAdvertising);
            Nan::SetPrototypeMethod(localRef, "stopAdvertising", StopAdvertising);
          



          
            Nan::SetAccessor(localRef->PrototypeTemplate(), Nan::New<String>("sdpRawAttributes").ToLocalChecked(), SdpRawAttributesGetter);
            Nan::SetAccessor(localRef->PrototypeTemplate(), Nan::New<String>("serviceId").ToLocalChecked(), ServiceIdGetter);

        Local<Object> constructor = Nan::To<Object>(Nan::GetFunction(localRef).ToLocalChecked()).ToLocalChecked();
        Nan::SetMethod(constructor, "castFrom", CastFrom);

        func = Nan::GetFunction(Nan::New<FunctionTemplate>(CreateAsync)).ToLocalChecked();
        Nan::Set(constructor, Nan::New<String>("createAsync").ToLocalChecked(), func);


        Nan::Set(exports, Nan::New<String>("RfcommServiceProvider").ToLocalChecked(), constructor);
      }

      virtual ::Platform::Object^ GetObjectInstance() const override {
        return _instance;
      }

    private:

      RfcommServiceProvider(::Windows::Devices::Bluetooth::Rfcomm::RfcommServiceProvider^ 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::Bluetooth::Rfcomm::RfcommServiceProvider^ winRtInstance;


      if (info.Length() == 1 && OpaqueWrapper::IsOpaqueWrapper(info[0]) &&
        NodeRT::Utils::IsWinRtWrapperOf<::Windows::Devices::Bluetooth::Rfcomm::RfcommServiceProvider^>(info[0])) {
        try {
          winRtInstance = (::Windows::Devices::Bluetooth::Rfcomm::RfcommServiceProvider^) 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());

      RfcommServiceProvider *wrapperInstance = new RfcommServiceProvider(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::Bluetooth::Rfcomm::RfcommServiceProvider^>(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::Bluetooth::Rfcomm::RfcommServiceProvider^ winRtInstance;
      try {
        winRtInstance = (::Windows::Devices::Bluetooth::Rfcomm::RfcommServiceProvider^) NodeRT::Utils::GetObjectInstance(info[0]);
      } catch (Platform::Exception ^exception) {
        NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
        return;
      }

      info.GetReturnValue().Set(WrapRfcommServiceProvider(winRtInstance));
    }


    static void StartAdvertising(Nan::NAN_METHOD_ARGS_TYPE info) {
      HandleScope scope;

      if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::Devices::Bluetooth::Rfcomm::RfcommServiceProvider^>(info.This())) {
        return;
      }

      RfcommServiceProvider *wrapper = RfcommServiceProvider::Unwrap<RfcommServiceProvider>(info.This());

      if (info.Length() == 1
        && NodeRT::Utils::IsWinRtWrapperOf<::Windows::Networking::Sockets::StreamSocketListener^>(info[0]))
      {
        try
        {
          ::Windows::Networking::Sockets::StreamSocketListener^ arg0 = dynamic_cast<::Windows::Networking::Sockets::StreamSocketListener^>(NodeRT::Utils::GetObjectInstance(info[0]));
          
          wrapper->_instance->StartAdvertising(arg0);
          return;
        } catch (Platform::Exception ^exception) {
          NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
          return;
        }
      }
      else if (info.Length() == 2
        && NodeRT::Utils::IsWinRtWrapperOf<::Windows::Networking::Sockets::StreamSocketListener^>(info[0])
        && info[1]->IsBoolean())
      {
        try
        {
          ::Windows::Networking::Sockets::StreamSocketListener^ arg0 = dynamic_cast<::Windows::Networking::Sockets::StreamSocketListener^>(NodeRT::Utils::GetObjectInstance(info[0]));
          bool arg1 = Nan::To<bool>(info[1]).FromMaybe(false);
          
          wrapper->_instance->StartAdvertising(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 StopAdvertising(Nan::NAN_METHOD_ARGS_TYPE info) {
      HandleScope scope;

      if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::Devices::Bluetooth::Rfcomm::RfcommServiceProvider^>(info.This())) {
        return;
      }

      RfcommServiceProvider *wrapper = RfcommServiceProvider::Unwrap<RfcommServiceProvider>(info.This());

      if (info.Length() == 0)
      {
        try
        {
          wrapper->_instance->StopAdvertising();
          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 CreateAsync(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::Bluetooth::Rfcomm::RfcommServiceProvider^>^ op;


      if (info.Length() == 2
          && NodeRT::Utils::IsWinRtWrapperOf<::Windows::Devices::Bluetooth::Rfcomm::RfcommServiceId^>(info[0]))
      {
        try
        {
          ::Windows::Devices::Bluetooth::Rfcomm::RfcommServiceId^ arg0 = UnwrapRfcommServiceId(info[0]);
            
          op = ::Windows::Devices::Bluetooth::Rfcomm::RfcommServiceProvider::CreateAsync(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::Bluetooth::Rfcomm::RfcommServiceProvider^> t)
      {
        try {
          auto result = t.get();
          NodeUtils::Async::RunCallbackOnMain(asyncToken, [result](NodeUtils::InvokeCallbackDelegate invokeCallback) {


            Local<Value> error;
            Local<Value> arg1;
            {
              TryCatch tryCatch;
              arg1 = WrapRfcommServiceProvider(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 SdpRawAttributesGetter(Local<String> property, const Nan::PropertyCallbackInfo<v8::Value> &info) {
      HandleScope scope;

      if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::Devices::Bluetooth::Rfcomm::RfcommServiceProvider^>(info.This())) {
        return;
      }

      RfcommServiceProvider *wrapper = RfcommServiceProvider::Unwrap<RfcommServiceProvider>(info.This());

      try  {
        ::Windows::Foundation::Collections::IMap<unsigned int, ::Windows::Storage::Streams::IBuffer^>^ result = wrapper->_instance->SdpRawAttributes;
        info.GetReturnValue().Set(NodeRT::Collections::MapWrapper<unsigned int,::Windows::Storage::Streams::IBuffer^>::CreateMapWrapper(result, 
            [](unsigned int val) -> Local<Value> {
              return Nan::New<Integer>(val);
            },
            [](Local<Value> value) -> bool {
              return value->IsUint32();
            },
            [](Local<Value> value) -> unsigned int {
              return static_cast<unsigned int>(Nan::To<uint32_t>(value).FromMaybe(0));
            },
            [](::Windows::Storage::Streams::IBuffer^ val) -> Local<Value> {
              return NodeRT::Utils::CreateExternalWinRTObject("Windows.Storage.Streams", "IBuffer", val);
            },
            [](Local<Value> value) -> bool {
              return NodeRT::Utils::IsWinRtWrapperOf<::Windows::Storage::Streams::IBuffer^>(value);
            },
            [](Local<Value> value) -> ::Windows::Storage::Streams::IBuffer^ {
              return dynamic_cast<::Windows::Storage::Streams::IBuffer^>(NodeRT::Utils::GetObjectInstance(value));
            }
          ));
        return;
      } catch (Platform::Exception ^exception) {
        NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
        return;
      }
    }
      
    static void ServiceIdGetter(Local<String> property, const Nan::PropertyCallbackInfo<v8::Value> &info) {
      HandleScope scope;

      if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::Devices::Bluetooth::Rfcomm::RfcommServiceProvider^>(info.This())) {
        return;
      }

      RfcommServiceProvider *wrapper = RfcommServiceProvider::Unwrap<RfcommServiceProvider>(info.This());

      try  {
        ::Windows::Devices::Bluetooth::Rfcomm::RfcommServiceId^ result = wrapper->_instance->ServiceId;
        info.GetReturnValue().Set(WrapRfcommServiceId(result));
        return;
      } catch (Platform::Exception ^exception) {
        NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
        return;
      }
    }
      


    private:
      ::Windows::Devices::Bluetooth::Rfcomm::RfcommServiceProvider^ _instance;
      static Persistent<FunctionTemplate> s_constructorTemplate;

      friend v8::Local<v8::Value> WrapRfcommServiceProvider(::Windows::Devices::Bluetooth::Rfcomm::RfcommServiceProvider^ wintRtInstance);
      friend ::Windows::Devices::Bluetooth::Rfcomm::RfcommServiceProvider^ UnwrapRfcommServiceProvider(Local<Value> value);
  };

  Persistent<FunctionTemplate> RfcommServiceProvider::s_constructorTemplate;

  v8::Local<v8::Value> WrapRfcommServiceProvider(::Windows::Devices::Bluetooth::Rfcomm::RfcommServiceProvider^ 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>(RfcommServiceProvider::s_constructorTemplate);
    return scope.Escape(Nan::NewInstance(Nan::GetFunction(localRef).ToLocalChecked(),_countof(args), args).ToLocalChecked());
  }

  ::Windows::Devices::Bluetooth::Rfcomm::RfcommServiceProvider^ UnwrapRfcommServiceProvider(Local<Value> value) {
     return RfcommServiceProvider::Unwrap<RfcommServiceProvider>(Nan::To<Object>(value).ToLocalChecked())->_instance;
  }

  void InitRfcommServiceProvider(Local<Object> exports) {
    RfcommServiceProvider::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::Bluetooth::Rfcomm::InitRfcommDeviceService(target);
      NodeRT::Windows::Devices::Bluetooth::Rfcomm::InitRfcommDeviceServicesResult(target);
      NodeRT::Windows::Devices::Bluetooth::Rfcomm::InitRfcommServiceId(target);
      NodeRT::Windows::Devices::Bluetooth::Rfcomm::InitRfcommServiceProvider(target);


  NodeRT::Utils::RegisterNameSpace("Windows.Devices.Bluetooth.Rfcomm", target);
}



NODE_MODULE(binding, init)
