// 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 Networking { namespace PushNotifications { 
  v8::Local<v8::Value> WrapPushNotificationChannel(::Windows::Networking::PushNotifications::PushNotificationChannel^ wintRtInstance);
  ::Windows::Networking::PushNotifications::PushNotificationChannel^ UnwrapPushNotificationChannel(Local<Value> value);
  
  v8::Local<v8::Value> WrapPushNotificationChannelManagerForUser(::Windows::Networking::PushNotifications::PushNotificationChannelManagerForUser^ wintRtInstance);
  ::Windows::Networking::PushNotifications::PushNotificationChannelManagerForUser^ UnwrapPushNotificationChannelManagerForUser(Local<Value> value);
  
  v8::Local<v8::Value> WrapPushNotificationReceivedEventArgs(::Windows::Networking::PushNotifications::PushNotificationReceivedEventArgs^ wintRtInstance);
  ::Windows::Networking::PushNotifications::PushNotificationReceivedEventArgs^ UnwrapPushNotificationReceivedEventArgs(Local<Value> value);
  
  v8::Local<v8::Value> WrapRawNotification(::Windows::Networking::PushNotifications::RawNotification^ wintRtInstance);
  ::Windows::Networking::PushNotifications::RawNotification^ UnwrapRawNotification(Local<Value> value);
  
  v8::Local<v8::Value> WrapPushNotificationChannelManager(::Windows::Networking::PushNotifications::PushNotificationChannelManager^ wintRtInstance);
  ::Windows::Networking::PushNotifications::PushNotificationChannelManager^ UnwrapPushNotificationChannelManager(Local<Value> value);
  



  static void InitPushNotificationTypeEnum(const Local<Object> exports) {
    HandleScope scope;

    Local<Object> enumObject = Nan::New<Object>();

    Nan::Set(exports, Nan::New<String>("PushNotificationType").ToLocalChecked(), enumObject);
    Nan::Set(enumObject, Nan::New<String>("toast").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::Networking::PushNotifications::PushNotificationType::Toast)));
    Nan::Set(enumObject, Nan::New<String>("tile").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::Networking::PushNotifications::PushNotificationType::Tile)));
    Nan::Set(enumObject, Nan::New<String>("badge").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::Networking::PushNotifications::PushNotificationType::Badge)));
    Nan::Set(enumObject, Nan::New<String>("raw").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::Networking::PushNotifications::PushNotificationType::Raw)));
    Nan::Set(enumObject, Nan::New<String>("tileFlyout").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::Networking::PushNotifications::PushNotificationType::TileFlyout)));
  }



  class PushNotificationChannel : 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>("PushNotificationChannel").ToLocalChecked());
        localRef->InstanceTemplate()->SetInternalFieldCount(1);


          
            Nan::SetPrototypeMethod(localRef, "close", Close);
          


          
          Nan::SetPrototypeMethod(localRef,"addListener", AddListener);
          Nan::SetPrototypeMethod(localRef,"on", AddListener);
          Nan::SetPrototypeMethod(localRef,"removeListener", RemoveListener);
          Nan::SetPrototypeMethod(localRef, "off", RemoveListener);

          
            Nan::SetAccessor(localRef->PrototypeTemplate(), Nan::New<String>("expirationTime").ToLocalChecked(), ExpirationTimeGetter);
            Nan::SetAccessor(localRef->PrototypeTemplate(), Nan::New<String>("uri").ToLocalChecked(), UriGetter);

        Local<Object> constructor = Nan::To<Object>(Nan::GetFunction(localRef).ToLocalChecked()).ToLocalChecked();
        Nan::SetMethod(constructor, "castFrom", CastFrom);



        Nan::Set(exports, Nan::New<String>("PushNotificationChannel").ToLocalChecked(), constructor);
      }

      virtual ::Platform::Object^ GetObjectInstance() const override {
        return _instance;
      }

    private:

      PushNotificationChannel(::Windows::Networking::PushNotifications::PushNotificationChannel^ 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::Networking::PushNotifications::PushNotificationChannel^ winRtInstance;


      if (info.Length() == 1 && OpaqueWrapper::IsOpaqueWrapper(info[0]) &&
        NodeRT::Utils::IsWinRtWrapperOf<::Windows::Networking::PushNotifications::PushNotificationChannel^>(info[0])) {
        try {
          winRtInstance = (::Windows::Networking::PushNotifications::PushNotificationChannel^) 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());

      PushNotificationChannel *wrapperInstance = new PushNotificationChannel(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::Networking::PushNotifications::PushNotificationChannel^>(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::Networking::PushNotifications::PushNotificationChannel^ winRtInstance;
      try {
        winRtInstance = (::Windows::Networking::PushNotifications::PushNotificationChannel^) NodeRT::Utils::GetObjectInstance(info[0]);
      } catch (Platform::Exception ^exception) {
        NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
        return;
      }

      info.GetReturnValue().Set(WrapPushNotificationChannel(winRtInstance));
    }


    static void Close(Nan::NAN_METHOD_ARGS_TYPE info) {
      HandleScope scope;

      if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::Networking::PushNotifications::PushNotificationChannel^>(info.This())) {
        return;
      }

      PushNotificationChannel *wrapper = PushNotificationChannel::Unwrap<PushNotificationChannel>(info.This());

      if (info.Length() == 0)
      {
        try
        {
          wrapper->_instance->Close();
          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 ExpirationTimeGetter(Local<String> property, const Nan::PropertyCallbackInfo<v8::Value> &info) {
      HandleScope scope;

      if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::Networking::PushNotifications::PushNotificationChannel^>(info.This())) {
        return;
      }

      PushNotificationChannel *wrapper = PushNotificationChannel::Unwrap<PushNotificationChannel>(info.This());

      try  {
        ::Windows::Foundation::DateTime result = wrapper->_instance->ExpirationTime;
        info.GetReturnValue().Set(NodeRT::Utils::DateTimeToJS(result));
        return;
      } catch (Platform::Exception ^exception) {
        NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
        return;
      }
    }
      
    static void UriGetter(Local<String> property, const Nan::PropertyCallbackInfo<v8::Value> &info) {
      HandleScope scope;

      if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::Networking::PushNotifications::PushNotificationChannel^>(info.This())) {
        return;
      }

      PushNotificationChannel *wrapper = PushNotificationChannel::Unwrap<PushNotificationChannel>(info.This());

      try  {
        Platform::String^ result = wrapper->_instance->Uri;
        info.GetReturnValue().Set(NodeRT::Utils::NewString(result->Data()));
        return;
      } catch (Platform::Exception ^exception) {
        NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
        return;
      }
    }
      


    static void AddListener(Nan::NAN_METHOD_ARGS_TYPE info) {
      HandleScope scope;

      if (info.Length() < 2 || !info[0]->IsString() || !info[1]->IsFunction()) {
        Nan::ThrowError(Nan::Error(NodeRT::Utils::NewString(L"wrong arguments, expected arguments are eventName(string),callback(function)")));
        return;
      }

      String::Value eventName(v8::Isolate::GetCurrent(), info[0]);
      auto str = *eventName;

      Local<Function> callback = info[1].As<Function>();

      ::Windows::Foundation::EventRegistrationToken registrationToken;
      if (NodeRT::Utils::CaseInsenstiveEquals(L"pushNotificationReceived", str))
      {
        if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::Networking::PushNotifications::PushNotificationChannel^>(info.This()))
        {
          Nan::ThrowError(Nan::Error(NodeRT::Utils::NewString(L"The caller of this method isn't of the expected type or internal WinRt object was disposed")));
      return;
        }
        PushNotificationChannel *wrapper = PushNotificationChannel::Unwrap<PushNotificationChannel>(info.This());
      
        try {
          Persistent<Object>* perstPtr = new Persistent<Object>();
          perstPtr->Reset(NodeRT::Utils::CreateCallbackObjectInDomain(callback));
          std::shared_ptr<Persistent<Object>> callbackObjPtr(perstPtr,
            [] (Persistent<Object> *ptr ) {
              NodeUtils::Async::RunOnMain([ptr]() {
                ptr->Reset();
                delete ptr;
            });
          });

          registrationToken = wrapper->_instance->PushNotificationReceived::add(
            ref new ::Windows::Foundation::TypedEventHandler<::Windows::Networking::PushNotifications::PushNotificationChannel^, ::Windows::Networking::PushNotifications::PushNotificationReceivedEventArgs^>(
            [callbackObjPtr](::Windows::Networking::PushNotifications::PushNotificationChannel^ arg0, ::Windows::Networking::PushNotifications::PushNotificationReceivedEventArgs^ arg1) {
              NodeUtils::Async::RunOnMain([callbackObjPtr , arg0, arg1]() {
                HandleScope scope;


                Local<Value> wrappedArg0;
                Local<Value> wrappedArg1;

                {
                  TryCatch tryCatch;


                  wrappedArg0 = WrapPushNotificationChannel(arg0);
                  wrappedArg1 = WrapPushNotificationReceivedEventArgs(arg1);


                  if (wrappedArg0.IsEmpty()) wrappedArg0 = Undefined();
                  if (wrappedArg1.IsEmpty()) wrappedArg1 = Undefined();
                }

                Local<Value> args[] = { wrappedArg0, wrappedArg1 };
                Local<Object> callbackObjLocalRef = Nan::New<Object>(*callbackObjPtr);
                NodeRT::Utils::CallCallbackInDomain(callbackObjLocalRef, _countof(args), args);
              });
            })
          );
        }
        catch (Platform::Exception ^exception) {
          NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
          return;
        }

      }
 else  {
        Nan::ThrowError(Nan::Error(String::Concat(v8::Isolate::GetCurrent(), NodeRT::Utils::NewString(L"given event name isn't supported: "), info[0].As<String>())));
        return;
      }

      Local<Value> tokenMapVal = NodeRT::Utils::GetHiddenValue(callback, Nan::New<String>(REGISTRATION_TOKEN_MAP_PROPERTY_NAME).ToLocalChecked());
      Local<Object> tokenMap;

      if (tokenMapVal.IsEmpty() || Nan::Equals(tokenMapVal, Undefined()).FromMaybe(false)) {
        tokenMap = Nan::New<Object>();
        NodeRT::Utils::SetHiddenValueWithObject(callback, Nan::New<String>(REGISTRATION_TOKEN_MAP_PROPERTY_NAME).ToLocalChecked(), tokenMap);
      } else {
        tokenMap = Nan::To<Object>(tokenMapVal).ToLocalChecked();
      }

      Nan::Set(tokenMap, info[0], CreateOpaqueWrapper(::Windows::Foundation::PropertyValue::CreateInt64(registrationToken.Value)));
    }

    static void RemoveListener(Nan::NAN_METHOD_ARGS_TYPE info) {
      HandleScope scope;

      if (info.Length() < 2 || !info[0]->IsString() || !info[1]->IsFunction()) {
        Nan::ThrowError(Nan::Error(NodeRT::Utils::NewString(L"wrong arguments, expected a string and a callback")));
        return;
      }

      String::Value eventName(v8::Isolate::GetCurrent(), info[0]);
      auto str = *eventName;

      if ((!NodeRT::Utils::CaseInsenstiveEquals(L"pushNotificationReceived", str))) {
        Nan::ThrowError(Nan::Error(String::Concat(v8::Isolate::GetCurrent(), NodeRT::Utils::NewString(L"given event name isn't supported: "), info[0].As<String>())));
        return;
      }

      Local<Function> callback = info[1].As<Function>();
      Local<Value> tokenMap = NodeRT::Utils::GetHiddenValue(callback, Nan::New<String>(REGISTRATION_TOKEN_MAP_PROPERTY_NAME).ToLocalChecked());

      if (tokenMap.IsEmpty() || Nan::Equals(tokenMap, Undefined()).FromMaybe(false)) {
        return;
      }

      Local<Value> opaqueWrapperObj =  Nan::Get(Nan::To<Object>(tokenMap).ToLocalChecked(), info[0]).ToLocalChecked();

      if (opaqueWrapperObj.IsEmpty() || Nan::Equals(opaqueWrapperObj,Undefined()).FromMaybe(false)) {
        return;
      }

      OpaqueWrapper *opaqueWrapper = OpaqueWrapper::Unwrap<OpaqueWrapper>(opaqueWrapperObj.As<Object>());

      long long tokenValue = (long long) opaqueWrapper->GetObjectInstance();
      ::Windows::Foundation::EventRegistrationToken registrationToken;
      registrationToken.Value = tokenValue;

      try  {
        if (NodeRT::Utils::CaseInsenstiveEquals(L"pushNotificationReceived", str)) {
          if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::Networking::PushNotifications::PushNotificationChannel^>(info.This()))
          {
            Nan::ThrowError(Nan::Error(NodeRT::Utils::NewString(L"The caller of this method isn't of the expected type or internal WinRt object was disposed")));
            return;
          }
          PushNotificationChannel *wrapper = PushNotificationChannel::Unwrap<PushNotificationChannel>(info.This());
          wrapper->_instance->PushNotificationReceived::remove(registrationToken);
        }
      } catch (Platform::Exception ^exception) {
        NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
      }

      Nan::Delete(Nan::To<Object>(tokenMap).ToLocalChecked(), Nan::To<String>(info[0]).ToLocalChecked());
    }
    private:
      ::Windows::Networking::PushNotifications::PushNotificationChannel^ _instance;
      static Persistent<FunctionTemplate> s_constructorTemplate;

      friend v8::Local<v8::Value> WrapPushNotificationChannel(::Windows::Networking::PushNotifications::PushNotificationChannel^ wintRtInstance);
      friend ::Windows::Networking::PushNotifications::PushNotificationChannel^ UnwrapPushNotificationChannel(Local<Value> value);
  };

  Persistent<FunctionTemplate> PushNotificationChannel::s_constructorTemplate;

  v8::Local<v8::Value> WrapPushNotificationChannel(::Windows::Networking::PushNotifications::PushNotificationChannel^ 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>(PushNotificationChannel::s_constructorTemplate);
    return scope.Escape(Nan::NewInstance(Nan::GetFunction(localRef).ToLocalChecked(),_countof(args), args).ToLocalChecked());
  }

  ::Windows::Networking::PushNotifications::PushNotificationChannel^ UnwrapPushNotificationChannel(Local<Value> value) {
     return PushNotificationChannel::Unwrap<PushNotificationChannel>(Nan::To<Object>(value).ToLocalChecked())->_instance;
  }

  void InitPushNotificationChannel(Local<Object> exports) {
    PushNotificationChannel::Init(exports);
  }

  class PushNotificationChannelManagerForUser : 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>("PushNotificationChannelManagerForUser").ToLocalChecked());
        localRef->InstanceTemplate()->SetInternalFieldCount(1);

        Local<Function> func;
        Local<FunctionTemplate> funcTemplate;


          
            Nan::SetPrototypeMethod(localRef, "createPushNotificationChannelForApplicationAsync", CreatePushNotificationChannelForApplicationAsync);
            Nan::SetPrototypeMethod(localRef, "createPushNotificationChannelForSecondaryTileAsync", CreatePushNotificationChannelForSecondaryTileAsync);
          


          
            Nan::SetAccessor(localRef->PrototypeTemplate(), Nan::New<String>("user").ToLocalChecked(), UserGetter);

        Local<Object> constructor = Nan::To<Object>(Nan::GetFunction(localRef).ToLocalChecked()).ToLocalChecked();
        Nan::SetMethod(constructor, "castFrom", CastFrom);



        Nan::Set(exports, Nan::New<String>("PushNotificationChannelManagerForUser").ToLocalChecked(), constructor);
      }

      virtual ::Platform::Object^ GetObjectInstance() const override {
        return _instance;
      }

    private:

      PushNotificationChannelManagerForUser(::Windows::Networking::PushNotifications::PushNotificationChannelManagerForUser^ 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::Networking::PushNotifications::PushNotificationChannelManagerForUser^ winRtInstance;


      if (info.Length() == 1 && OpaqueWrapper::IsOpaqueWrapper(info[0]) &&
        NodeRT::Utils::IsWinRtWrapperOf<::Windows::Networking::PushNotifications::PushNotificationChannelManagerForUser^>(info[0])) {
        try {
          winRtInstance = (::Windows::Networking::PushNotifications::PushNotificationChannelManagerForUser^) 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());

      PushNotificationChannelManagerForUser *wrapperInstance = new PushNotificationChannelManagerForUser(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::Networking::PushNotifications::PushNotificationChannelManagerForUser^>(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::Networking::PushNotifications::PushNotificationChannelManagerForUser^ winRtInstance;
      try {
        winRtInstance = (::Windows::Networking::PushNotifications::PushNotificationChannelManagerForUser^) NodeRT::Utils::GetObjectInstance(info[0]);
      } catch (Platform::Exception ^exception) {
        NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
        return;
      }

      info.GetReturnValue().Set(WrapPushNotificationChannelManagerForUser(winRtInstance));
    }

    static void CreatePushNotificationChannelForApplicationAsync(Nan::NAN_METHOD_ARGS_TYPE info) {
      HandleScope scope;

      if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::Networking::PushNotifications::PushNotificationChannelManagerForUser^>(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;
      }

      PushNotificationChannelManagerForUser *wrapper = PushNotificationChannelManagerForUser::Unwrap<PushNotificationChannelManagerForUser>(info.This());

      ::Windows::Foundation::IAsyncOperation<::Windows::Networking::PushNotifications::PushNotificationChannel^>^ op;


      if (info.Length() == 1)
      {
        try
        {
          op = wrapper->_instance->CreatePushNotificationChannelForApplicationAsync();
        }
        catch (Platform::Exception ^exception)
        {
          NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
          return;
        }
      }
      else 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 = wrapper->_instance->CreatePushNotificationChannelForApplicationAsync(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::Networking::PushNotifications::PushNotificationChannel^> t) {
        try {
          auto result = t.get();
          NodeUtils::Async::RunCallbackOnMain(asyncToken, [result](NodeUtils::InvokeCallbackDelegate invokeCallback) {


            Local<Value> error;
            Local<Value> arg1;
            {
              TryCatch tryCatch;
              arg1 = WrapPushNotificationChannel(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 CreatePushNotificationChannelForSecondaryTileAsync(Nan::NAN_METHOD_ARGS_TYPE info) {
      HandleScope scope;

      if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::Networking::PushNotifications::PushNotificationChannelManagerForUser^>(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;
      }

      PushNotificationChannelManagerForUser *wrapper = PushNotificationChannelManagerForUser::Unwrap<PushNotificationChannelManagerForUser>(info.This());

      ::Windows::Foundation::IAsyncOperation<::Windows::Networking::PushNotifications::PushNotificationChannel^>^ 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 = wrapper->_instance->CreatePushNotificationChannelForSecondaryTileAsync(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::Networking::PushNotifications::PushNotificationChannel^> t) {
        try {
          auto result = t.get();
          NodeUtils::Async::RunCallbackOnMain(asyncToken, [result](NodeUtils::InvokeCallbackDelegate invokeCallback) {


            Local<Value> error;
            Local<Value> arg1;
            {
              TryCatch tryCatch;
              arg1 = WrapPushNotificationChannel(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 UserGetter(Local<String> property, const Nan::PropertyCallbackInfo<v8::Value> &info) {
      HandleScope scope;

      if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::Networking::PushNotifications::PushNotificationChannelManagerForUser^>(info.This())) {
        return;
      }

      PushNotificationChannelManagerForUser *wrapper = PushNotificationChannelManagerForUser::Unwrap<PushNotificationChannelManagerForUser>(info.This());

      try  {
        ::Windows::System::User^ result = wrapper->_instance->User;
        info.GetReturnValue().Set(NodeRT::Utils::CreateExternalWinRTObject("Windows.System", "User", result));
        return;
      } catch (Platform::Exception ^exception) {
        NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
        return;
      }
    }
      


    private:
      ::Windows::Networking::PushNotifications::PushNotificationChannelManagerForUser^ _instance;
      static Persistent<FunctionTemplate> s_constructorTemplate;

      friend v8::Local<v8::Value> WrapPushNotificationChannelManagerForUser(::Windows::Networking::PushNotifications::PushNotificationChannelManagerForUser^ wintRtInstance);
      friend ::Windows::Networking::PushNotifications::PushNotificationChannelManagerForUser^ UnwrapPushNotificationChannelManagerForUser(Local<Value> value);
  };

  Persistent<FunctionTemplate> PushNotificationChannelManagerForUser::s_constructorTemplate;

  v8::Local<v8::Value> WrapPushNotificationChannelManagerForUser(::Windows::Networking::PushNotifications::PushNotificationChannelManagerForUser^ 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>(PushNotificationChannelManagerForUser::s_constructorTemplate);
    return scope.Escape(Nan::NewInstance(Nan::GetFunction(localRef).ToLocalChecked(),_countof(args), args).ToLocalChecked());
  }

  ::Windows::Networking::PushNotifications::PushNotificationChannelManagerForUser^ UnwrapPushNotificationChannelManagerForUser(Local<Value> value) {
     return PushNotificationChannelManagerForUser::Unwrap<PushNotificationChannelManagerForUser>(Nan::To<Object>(value).ToLocalChecked())->_instance;
  }

  void InitPushNotificationChannelManagerForUser(Local<Object> exports) {
    PushNotificationChannelManagerForUser::Init(exports);
  }

  class PushNotificationReceivedEventArgs : 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>("PushNotificationReceivedEventArgs").ToLocalChecked());
        localRef->InstanceTemplate()->SetInternalFieldCount(1);





          
            Nan::SetAccessor(localRef->PrototypeTemplate(), Nan::New<String>("cancel").ToLocalChecked(), CancelGetter, CancelSetter);
            Nan::SetAccessor(localRef->PrototypeTemplate(), Nan::New<String>("badgeNotification").ToLocalChecked(), BadgeNotificationGetter);
            Nan::SetAccessor(localRef->PrototypeTemplate(), Nan::New<String>("notificationType").ToLocalChecked(), NotificationTypeGetter);
            Nan::SetAccessor(localRef->PrototypeTemplate(), Nan::New<String>("rawNotification").ToLocalChecked(), RawNotificationGetter);
            Nan::SetAccessor(localRef->PrototypeTemplate(), Nan::New<String>("tileNotification").ToLocalChecked(), TileNotificationGetter);
            Nan::SetAccessor(localRef->PrototypeTemplate(), Nan::New<String>("toastNotification").ToLocalChecked(), ToastNotificationGetter);

        Local<Object> constructor = Nan::To<Object>(Nan::GetFunction(localRef).ToLocalChecked()).ToLocalChecked();
        Nan::SetMethod(constructor, "castFrom", CastFrom);



        Nan::Set(exports, Nan::New<String>("PushNotificationReceivedEventArgs").ToLocalChecked(), constructor);
      }

      virtual ::Platform::Object^ GetObjectInstance() const override {
        return _instance;
      }

    private:

      PushNotificationReceivedEventArgs(::Windows::Networking::PushNotifications::PushNotificationReceivedEventArgs^ 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::Networking::PushNotifications::PushNotificationReceivedEventArgs^ winRtInstance;


      if (info.Length() == 1 && OpaqueWrapper::IsOpaqueWrapper(info[0]) &&
        NodeRT::Utils::IsWinRtWrapperOf<::Windows::Networking::PushNotifications::PushNotificationReceivedEventArgs^>(info[0])) {
        try {
          winRtInstance = (::Windows::Networking::PushNotifications::PushNotificationReceivedEventArgs^) 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());

      PushNotificationReceivedEventArgs *wrapperInstance = new PushNotificationReceivedEventArgs(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::Networking::PushNotifications::PushNotificationReceivedEventArgs^>(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::Networking::PushNotifications::PushNotificationReceivedEventArgs^ winRtInstance;
      try {
        winRtInstance = (::Windows::Networking::PushNotifications::PushNotificationReceivedEventArgs^) NodeRT::Utils::GetObjectInstance(info[0]);
      } catch (Platform::Exception ^exception) {
        NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
        return;
      }

      info.GetReturnValue().Set(WrapPushNotificationReceivedEventArgs(winRtInstance));
    }





    static void CancelGetter(Local<String> property, const Nan::PropertyCallbackInfo<v8::Value> &info) {
      HandleScope scope;

      if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::Networking::PushNotifications::PushNotificationReceivedEventArgs^>(info.This())) {
        return;
      }

      PushNotificationReceivedEventArgs *wrapper = PushNotificationReceivedEventArgs::Unwrap<PushNotificationReceivedEventArgs>(info.This());

      try  {
        bool result = wrapper->_instance->Cancel;
        info.GetReturnValue().Set(Nan::New<Boolean>(result));
        return;
      } catch (Platform::Exception ^exception) {
        NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
        return;
      }
    }
      
    static void CancelSetter(Local<String> property, Local<Value> value, const Nan::PropertyCallbackInfo<void> &info) {
      HandleScope scope;

      if (!value->IsBoolean()) {
        Nan::ThrowError(Nan::Error(NodeRT::Utils::NewString(L"Value to set is of unexpected type")));
        return;
      }

      if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::Networking::PushNotifications::PushNotificationReceivedEventArgs^>(info.This())) {
        return;
      }

      PushNotificationReceivedEventArgs *wrapper = PushNotificationReceivedEventArgs::Unwrap<PushNotificationReceivedEventArgs>(info.This());

      try {

        bool winRtValue = Nan::To<bool>(value).FromMaybe(false);

        wrapper->_instance->Cancel = winRtValue;
      } catch (Platform::Exception ^exception) {
        NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
      }
    }
      
    static void BadgeNotificationGetter(Local<String> property, const Nan::PropertyCallbackInfo<v8::Value> &info) {
      HandleScope scope;

      if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::Networking::PushNotifications::PushNotificationReceivedEventArgs^>(info.This())) {
        return;
      }

      PushNotificationReceivedEventArgs *wrapper = PushNotificationReceivedEventArgs::Unwrap<PushNotificationReceivedEventArgs>(info.This());

      try  {
        ::Windows::UI::Notifications::BadgeNotification^ result = wrapper->_instance->BadgeNotification;
        info.GetReturnValue().Set(NodeRT::Utils::CreateExternalWinRTObject("Windows.UI.Notifications", "BadgeNotification", result));
        return;
      } catch (Platform::Exception ^exception) {
        NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
        return;
      }
    }
      
    static void NotificationTypeGetter(Local<String> property, const Nan::PropertyCallbackInfo<v8::Value> &info) {
      HandleScope scope;

      if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::Networking::PushNotifications::PushNotificationReceivedEventArgs^>(info.This())) {
        return;
      }

      PushNotificationReceivedEventArgs *wrapper = PushNotificationReceivedEventArgs::Unwrap<PushNotificationReceivedEventArgs>(info.This());

      try  {
        ::Windows::Networking::PushNotifications::PushNotificationType result = wrapper->_instance->NotificationType;
        info.GetReturnValue().Set(Nan::New<Integer>(static_cast<int>(result)));
        return;
      } catch (Platform::Exception ^exception) {
        NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
        return;
      }
    }
      
    static void RawNotificationGetter(Local<String> property, const Nan::PropertyCallbackInfo<v8::Value> &info) {
      HandleScope scope;

      if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::Networking::PushNotifications::PushNotificationReceivedEventArgs^>(info.This())) {
        return;
      }

      PushNotificationReceivedEventArgs *wrapper = PushNotificationReceivedEventArgs::Unwrap<PushNotificationReceivedEventArgs>(info.This());

      try  {
        ::Windows::Networking::PushNotifications::RawNotification^ result = wrapper->_instance->RawNotification;
        info.GetReturnValue().Set(WrapRawNotification(result));
        return;
      } catch (Platform::Exception ^exception) {
        NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
        return;
      }
    }
      
    static void TileNotificationGetter(Local<String> property, const Nan::PropertyCallbackInfo<v8::Value> &info) {
      HandleScope scope;

      if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::Networking::PushNotifications::PushNotificationReceivedEventArgs^>(info.This())) {
        return;
      }

      PushNotificationReceivedEventArgs *wrapper = PushNotificationReceivedEventArgs::Unwrap<PushNotificationReceivedEventArgs>(info.This());

      try  {
        ::Windows::UI::Notifications::TileNotification^ result = wrapper->_instance->TileNotification;
        info.GetReturnValue().Set(NodeRT::Utils::CreateExternalWinRTObject("Windows.UI.Notifications", "TileNotification", result));
        return;
      } catch (Platform::Exception ^exception) {
        NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
        return;
      }
    }
      
    static void ToastNotificationGetter(Local<String> property, const Nan::PropertyCallbackInfo<v8::Value> &info) {
      HandleScope scope;

      if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::Networking::PushNotifications::PushNotificationReceivedEventArgs^>(info.This())) {
        return;
      }

      PushNotificationReceivedEventArgs *wrapper = PushNotificationReceivedEventArgs::Unwrap<PushNotificationReceivedEventArgs>(info.This());

      try  {
        ::Windows::UI::Notifications::ToastNotification^ result = wrapper->_instance->ToastNotification;
        info.GetReturnValue().Set(NodeRT::Utils::CreateExternalWinRTObject("Windows.UI.Notifications", "ToastNotification", result));
        return;
      } catch (Platform::Exception ^exception) {
        NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
        return;
      }
    }
      


    private:
      ::Windows::Networking::PushNotifications::PushNotificationReceivedEventArgs^ _instance;
      static Persistent<FunctionTemplate> s_constructorTemplate;

      friend v8::Local<v8::Value> WrapPushNotificationReceivedEventArgs(::Windows::Networking::PushNotifications::PushNotificationReceivedEventArgs^ wintRtInstance);
      friend ::Windows::Networking::PushNotifications::PushNotificationReceivedEventArgs^ UnwrapPushNotificationReceivedEventArgs(Local<Value> value);
  };

  Persistent<FunctionTemplate> PushNotificationReceivedEventArgs::s_constructorTemplate;

  v8::Local<v8::Value> WrapPushNotificationReceivedEventArgs(::Windows::Networking::PushNotifications::PushNotificationReceivedEventArgs^ 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>(PushNotificationReceivedEventArgs::s_constructorTemplate);
    return scope.Escape(Nan::NewInstance(Nan::GetFunction(localRef).ToLocalChecked(),_countof(args), args).ToLocalChecked());
  }

  ::Windows::Networking::PushNotifications::PushNotificationReceivedEventArgs^ UnwrapPushNotificationReceivedEventArgs(Local<Value> value) {
     return PushNotificationReceivedEventArgs::Unwrap<PushNotificationReceivedEventArgs>(Nan::To<Object>(value).ToLocalChecked())->_instance;
  }

  void InitPushNotificationReceivedEventArgs(Local<Object> exports) {
    PushNotificationReceivedEventArgs::Init(exports);
  }

  class RawNotification : 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>("RawNotification").ToLocalChecked());
        localRef->InstanceTemplate()->SetInternalFieldCount(1);





          
            Nan::SetAccessor(localRef->PrototypeTemplate(), Nan::New<String>("content").ToLocalChecked(), ContentGetter);

        Local<Object> constructor = Nan::To<Object>(Nan::GetFunction(localRef).ToLocalChecked()).ToLocalChecked();
        Nan::SetMethod(constructor, "castFrom", CastFrom);



        Nan::Set(exports, Nan::New<String>("RawNotification").ToLocalChecked(), constructor);
      }

      virtual ::Platform::Object^ GetObjectInstance() const override {
        return _instance;
      }

    private:

      RawNotification(::Windows::Networking::PushNotifications::RawNotification^ 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::Networking::PushNotifications::RawNotification^ winRtInstance;


      if (info.Length() == 1 && OpaqueWrapper::IsOpaqueWrapper(info[0]) &&
        NodeRT::Utils::IsWinRtWrapperOf<::Windows::Networking::PushNotifications::RawNotification^>(info[0])) {
        try {
          winRtInstance = (::Windows::Networking::PushNotifications::RawNotification^) 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());

      RawNotification *wrapperInstance = new RawNotification(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::Networking::PushNotifications::RawNotification^>(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::Networking::PushNotifications::RawNotification^ winRtInstance;
      try {
        winRtInstance = (::Windows::Networking::PushNotifications::RawNotification^) NodeRT::Utils::GetObjectInstance(info[0]);
      } catch (Platform::Exception ^exception) {
        NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
        return;
      }

      info.GetReturnValue().Set(WrapRawNotification(winRtInstance));
    }





    static void ContentGetter(Local<String> property, const Nan::PropertyCallbackInfo<v8::Value> &info) {
      HandleScope scope;

      if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::Networking::PushNotifications::RawNotification^>(info.This())) {
        return;
      }

      RawNotification *wrapper = RawNotification::Unwrap<RawNotification>(info.This());

      try  {
        Platform::String^ result = wrapper->_instance->Content;
        info.GetReturnValue().Set(NodeRT::Utils::NewString(result->Data()));
        return;
      } catch (Platform::Exception ^exception) {
        NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
        return;
      }
    }
      


    private:
      ::Windows::Networking::PushNotifications::RawNotification^ _instance;
      static Persistent<FunctionTemplate> s_constructorTemplate;

      friend v8::Local<v8::Value> WrapRawNotification(::Windows::Networking::PushNotifications::RawNotification^ wintRtInstance);
      friend ::Windows::Networking::PushNotifications::RawNotification^ UnwrapRawNotification(Local<Value> value);
  };

  Persistent<FunctionTemplate> RawNotification::s_constructorTemplate;

  v8::Local<v8::Value> WrapRawNotification(::Windows::Networking::PushNotifications::RawNotification^ 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>(RawNotification::s_constructorTemplate);
    return scope.Escape(Nan::NewInstance(Nan::GetFunction(localRef).ToLocalChecked(),_countof(args), args).ToLocalChecked());
  }

  ::Windows::Networking::PushNotifications::RawNotification^ UnwrapRawNotification(Local<Value> value) {
     return RawNotification::Unwrap<RawNotification>(Nan::To<Object>(value).ToLocalChecked())->_instance;
  }

  void InitRawNotification(Local<Object> exports) {
    RawNotification::Init(exports);
  }

  class PushNotificationChannelManager : 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>("PushNotificationChannelManager").ToLocalChecked());
        localRef->InstanceTemplate()->SetInternalFieldCount(1);

        Local<Function> func;
        Local<FunctionTemplate> funcTemplate;





        Local<Object> constructor = Nan::To<Object>(Nan::GetFunction(localRef).ToLocalChecked()).ToLocalChecked();
        Nan::SetMethod(constructor, "castFrom", CastFrom);

        Nan::SetMethod(constructor, "getForUser", GetForUser);
        func = Nan::GetFunction(Nan::New<FunctionTemplate>(CreatePushNotificationChannelForApplicationAsync)).ToLocalChecked();
        Nan::Set(constructor, Nan::New<String>("createPushNotificationChannelForApplicationAsync").ToLocalChecked(), func);
        func = Nan::GetFunction(Nan::New<FunctionTemplate>(CreatePushNotificationChannelForSecondaryTileAsync)).ToLocalChecked();
        Nan::Set(constructor, Nan::New<String>("createPushNotificationChannelForSecondaryTileAsync").ToLocalChecked(), func);


        Nan::Set(exports, Nan::New<String>("PushNotificationChannelManager").ToLocalChecked(), constructor);
      }

      virtual ::Platform::Object^ GetObjectInstance() const override {
        return _instance;
      }

    private:

      PushNotificationChannelManager(::Windows::Networking::PushNotifications::PushNotificationChannelManager^ 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::Networking::PushNotifications::PushNotificationChannelManager^ winRtInstance;


      if (info.Length() == 1 && OpaqueWrapper::IsOpaqueWrapper(info[0]) &&
        NodeRT::Utils::IsWinRtWrapperOf<::Windows::Networking::PushNotifications::PushNotificationChannelManager^>(info[0])) {
        try {
          winRtInstance = (::Windows::Networking::PushNotifications::PushNotificationChannelManager^) 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());

      PushNotificationChannelManager *wrapperInstance = new PushNotificationChannelManager(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::Networking::PushNotifications::PushNotificationChannelManager^>(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::Networking::PushNotifications::PushNotificationChannelManager^ winRtInstance;
      try {
        winRtInstance = (::Windows::Networking::PushNotifications::PushNotificationChannelManager^) NodeRT::Utils::GetObjectInstance(info[0]);
      } catch (Platform::Exception ^exception) {
        NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
        return;
      }

      info.GetReturnValue().Set(WrapPushNotificationChannelManager(winRtInstance));
    }




    static void CreatePushNotificationChannelForApplicationAsync(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::Networking::PushNotifications::PushNotificationChannel^>^ op;


      if (info.Length() == 1)
      {
        try
        {
          op = ::Windows::Networking::PushNotifications::PushNotificationChannelManager::CreatePushNotificationChannelForApplicationAsync();
        } catch (Platform::Exception ^exception) {
            NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
            return;
        }
      }
      else 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::Networking::PushNotifications::PushNotificationChannelManager::CreatePushNotificationChannelForApplicationAsync(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::Networking::PushNotifications::PushNotificationChannel^> t)
      {
        try {
          auto result = t.get();
          NodeUtils::Async::RunCallbackOnMain(asyncToken, [result](NodeUtils::InvokeCallbackDelegate invokeCallback) {


            Local<Value> error;
            Local<Value> arg1;
            {
              TryCatch tryCatch;
              arg1 = WrapPushNotificationChannel(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 CreatePushNotificationChannelForSecondaryTileAsync(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::Networking::PushNotifications::PushNotificationChannel^>^ 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::Networking::PushNotifications::PushNotificationChannelManager::CreatePushNotificationChannelForSecondaryTileAsync(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::Networking::PushNotifications::PushNotificationChannel^> t)
      {
        try {
          auto result = t.get();
          NodeUtils::Async::RunCallbackOnMain(asyncToken, [result](NodeUtils::InvokeCallbackDelegate invokeCallback) {


            Local<Value> error;
            Local<Value> arg1;
            {
              TryCatch tryCatch;
              arg1 = WrapPushNotificationChannel(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 GetForUser(Nan::NAN_METHOD_ARGS_TYPE info) {
      HandleScope scope;

      if (info.Length() == 1
        && NodeRT::Utils::IsWinRtWrapperOf<::Windows::System::User^>(info[0]))
      {
        try
        {
          ::Windows::System::User^ arg0 = dynamic_cast<::Windows::System::User^>(NodeRT::Utils::GetObjectInstance(info[0]));
          
          ::Windows::Networking::PushNotifications::PushNotificationChannelManagerForUser^ result;
          result = ::Windows::Networking::PushNotifications::PushNotificationChannelManager::GetForUser(arg0);
          info.GetReturnValue().Set(WrapPushNotificationChannelManagerForUser(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;
      }
    }



    private:
      ::Windows::Networking::PushNotifications::PushNotificationChannelManager^ _instance;
      static Persistent<FunctionTemplate> s_constructorTemplate;

      friend v8::Local<v8::Value> WrapPushNotificationChannelManager(::Windows::Networking::PushNotifications::PushNotificationChannelManager^ wintRtInstance);
      friend ::Windows::Networking::PushNotifications::PushNotificationChannelManager^ UnwrapPushNotificationChannelManager(Local<Value> value);
  };

  Persistent<FunctionTemplate> PushNotificationChannelManager::s_constructorTemplate;

  v8::Local<v8::Value> WrapPushNotificationChannelManager(::Windows::Networking::PushNotifications::PushNotificationChannelManager^ 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>(PushNotificationChannelManager::s_constructorTemplate);
    return scope.Escape(Nan::NewInstance(Nan::GetFunction(localRef).ToLocalChecked(),_countof(args), args).ToLocalChecked());
  }

  ::Windows::Networking::PushNotifications::PushNotificationChannelManager^ UnwrapPushNotificationChannelManager(Local<Value> value) {
     return PushNotificationChannelManager::Unwrap<PushNotificationChannelManager>(Nan::To<Object>(value).ToLocalChecked())->_instance;
  }

  void InitPushNotificationChannelManager(Local<Object> exports) {
    PushNotificationChannelManager::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::Networking::PushNotifications::InitPushNotificationTypeEnum(target);
      NodeRT::Windows::Networking::PushNotifications::InitPushNotificationChannel(target);
      NodeRT::Windows::Networking::PushNotifications::InitPushNotificationChannelManagerForUser(target);
      NodeRT::Windows::Networking::PushNotifications::InitPushNotificationReceivedEventArgs(target);
      NodeRT::Windows::Networking::PushNotifications::InitRawNotification(target);
      NodeRT::Windows::Networking::PushNotifications::InitPushNotificationChannelManager(target);


  NodeRT::Utils::RegisterNameSpace("Windows.Networking.PushNotifications", target);
}



NODE_MODULE(binding, init)
