// Copyright (c) Microsoft Corporation
// 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::Handle;
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 Media { namespace Protection { 

  v8::Local<v8::Value> WrapMediaProtectionManager(::Windows::Media::Protection::MediaProtectionManager^ wintRtInstance);
  ::Windows::Media::Protection::MediaProtectionManager^ UnwrapMediaProtectionManager(Local<Value> value);
  
  v8::Local<v8::Value> WrapServiceRequestedEventArgs(::Windows::Media::Protection::ServiceRequestedEventArgs^ wintRtInstance);
  ::Windows::Media::Protection::ServiceRequestedEventArgs^ UnwrapServiceRequestedEventArgs(Local<Value> value);
  
  v8::Local<v8::Value> WrapComponentLoadFailedEventArgs(::Windows::Media::Protection::ComponentLoadFailedEventArgs^ wintRtInstance);
  ::Windows::Media::Protection::ComponentLoadFailedEventArgs^ UnwrapComponentLoadFailedEventArgs(Local<Value> value);
  
  v8::Local<v8::Value> WrapMediaProtectionServiceCompletion(::Windows::Media::Protection::MediaProtectionServiceCompletion^ wintRtInstance);
  ::Windows::Media::Protection::MediaProtectionServiceCompletion^ UnwrapMediaProtectionServiceCompletion(Local<Value> value);
  
  v8::Local<v8::Value> WrapRevocationAndRenewalInformation(::Windows::Media::Protection::RevocationAndRenewalInformation^ wintRtInstance);
  ::Windows::Media::Protection::RevocationAndRenewalInformation^ UnwrapRevocationAndRenewalInformation(Local<Value> value);
  
  v8::Local<v8::Value> WrapRevocationAndRenewalItem(::Windows::Media::Protection::RevocationAndRenewalItem^ wintRtInstance);
  ::Windows::Media::Protection::RevocationAndRenewalItem^ UnwrapRevocationAndRenewalItem(Local<Value> value);
  
  v8::Local<v8::Value> WrapMediaProtectionPMPServer(::Windows::Media::Protection::MediaProtectionPMPServer^ wintRtInstance);
  ::Windows::Media::Protection::MediaProtectionPMPServer^ UnwrapMediaProtectionPMPServer(Local<Value> value);
  
  v8::Local<v8::Value> WrapIMediaProtectionServiceRequest(::Windows::Media::Protection::IMediaProtectionServiceRequest^ wintRtInstance);
  ::Windows::Media::Protection::IMediaProtectionServiceRequest^ UnwrapIMediaProtectionServiceRequest(Local<Value> value);
  
  v8::Local<v8::Value> WrapProtectionCapabilities(::Windows::Media::Protection::ProtectionCapabilities^ wintRtInstance);
  ::Windows::Media::Protection::ProtectionCapabilities^ UnwrapProtectionCapabilities(Local<Value> value);
  
  v8::Local<v8::Value> WrapComponentRenewal(::Windows::Media::Protection::ComponentRenewal^ wintRtInstance);
  ::Windows::Media::Protection::ComponentRenewal^ UnwrapComponentRenewal(Local<Value> value);
  


  static void InitRevocationAndRenewalReasonsEnum(const Local<Object> exports)
  {
    HandleScope scope;
    
	Local<Object> enumObject = Nan::New<Object>();
    Nan::Set(exports, Nan::New<String>("RevocationAndRenewalReasons").ToLocalChecked(), enumObject);
	Nan::Set(enumObject, Nan::New<String>("userModeComponentLoad").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::Media::Protection::RevocationAndRenewalReasons::UserModeComponentLoad)));
	Nan::Set(enumObject, Nan::New<String>("kernelModeComponentLoad").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::Media::Protection::RevocationAndRenewalReasons::KernelModeComponentLoad)));
	Nan::Set(enumObject, Nan::New<String>("appComponent").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::Media::Protection::RevocationAndRenewalReasons::AppComponent)));
	Nan::Set(enumObject, Nan::New<String>("globalRevocationListLoadFailed").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::Media::Protection::RevocationAndRenewalReasons::GlobalRevocationListLoadFailed)));
	Nan::Set(enumObject, Nan::New<String>("invalidGlobalRevocationListSignature").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::Media::Protection::RevocationAndRenewalReasons::InvalidGlobalRevocationListSignature)));
	Nan::Set(enumObject, Nan::New<String>("globalRevocationListAbsent").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::Media::Protection::RevocationAndRenewalReasons::GlobalRevocationListAbsent)));
	Nan::Set(enumObject, Nan::New<String>("componentRevoked").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::Media::Protection::RevocationAndRenewalReasons::ComponentRevoked)));
	Nan::Set(enumObject, Nan::New<String>("invalidComponentCertificateExtendedKeyUse").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::Media::Protection::RevocationAndRenewalReasons::InvalidComponentCertificateExtendedKeyUse)));
	Nan::Set(enumObject, Nan::New<String>("componentCertificateRevoked").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::Media::Protection::RevocationAndRenewalReasons::ComponentCertificateRevoked)));
	Nan::Set(enumObject, Nan::New<String>("invalidComponentCertificateRoot").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::Media::Protection::RevocationAndRenewalReasons::InvalidComponentCertificateRoot)));
	Nan::Set(enumObject, Nan::New<String>("componentHighSecurityCertificateRevoked").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::Media::Protection::RevocationAndRenewalReasons::ComponentHighSecurityCertificateRevoked)));
	Nan::Set(enumObject, Nan::New<String>("componentLowSecurityCertificateRevoked").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::Media::Protection::RevocationAndRenewalReasons::ComponentLowSecurityCertificateRevoked)));
	Nan::Set(enumObject, Nan::New<String>("bootDriverVerificationFailed").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::Media::Protection::RevocationAndRenewalReasons::BootDriverVerificationFailed)));
	Nan::Set(enumObject, Nan::New<String>("componentSignedWithTestCertificate").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::Media::Protection::RevocationAndRenewalReasons::ComponentSignedWithTestCertificate)));
	Nan::Set(enumObject, Nan::New<String>("encryptionFailure").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::Media::Protection::RevocationAndRenewalReasons::EncryptionFailure)));
  }


  static void InitGraphicsTrustStatusEnum(const Local<Object> exports)
  {
    HandleScope scope;
    
	Local<Object> enumObject = Nan::New<Object>();
    Nan::Set(exports, Nan::New<String>("GraphicsTrustStatus").ToLocalChecked(), enumObject);
	Nan::Set(enumObject, Nan::New<String>("trustNotRequired").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::Media::Protection::GraphicsTrustStatus::TrustNotRequired)));
	Nan::Set(enumObject, Nan::New<String>("trustEstablished").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::Media::Protection::GraphicsTrustStatus::TrustEstablished)));
	Nan::Set(enumObject, Nan::New<String>("environmentNotSupported").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::Media::Protection::GraphicsTrustStatus::EnvironmentNotSupported)));
	Nan::Set(enumObject, Nan::New<String>("driverNotSupported").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::Media::Protection::GraphicsTrustStatus::DriverNotSupported)));
	Nan::Set(enumObject, Nan::New<String>("driverSigningFailure").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::Media::Protection::GraphicsTrustStatus::DriverSigningFailure)));
	Nan::Set(enumObject, Nan::New<String>("unknownFailure").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::Media::Protection::GraphicsTrustStatus::UnknownFailure)));
  }


  static void InitProtectionCapabilityResultEnum(const Local<Object> exports)
  {
    HandleScope scope;
    
	Local<Object> enumObject = Nan::New<Object>();
    Nan::Set(exports, Nan::New<String>("ProtectionCapabilityResult").ToLocalChecked(), enumObject);
	Nan::Set(enumObject, Nan::New<String>("notSupported").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::Media::Protection::ProtectionCapabilityResult::NotSupported)));
	Nan::Set(enumObject, Nan::New<String>("maybe").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::Media::Protection::ProtectionCapabilityResult::Maybe)));
	Nan::Set(enumObject, Nan::New<String>("probably").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::Media::Protection::ProtectionCapabilityResult::Probably)));
  }


  static void InitRenewalStatusEnum(const Local<Object> exports)
  {
    HandleScope scope;
    
	Local<Object> enumObject = Nan::New<Object>();
    Nan::Set(exports, Nan::New<String>("RenewalStatus").ToLocalChecked(), enumObject);
	Nan::Set(enumObject, Nan::New<String>("notStarted").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::Media::Protection::RenewalStatus::NotStarted)));
	Nan::Set(enumObject, Nan::New<String>("updatesInProgress").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::Media::Protection::RenewalStatus::UpdatesInProgress)));
	Nan::Set(enumObject, Nan::New<String>("userCancelled").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::Media::Protection::RenewalStatus::UserCancelled)));
	Nan::Set(enumObject, Nan::New<String>("appComponentsMayNeedUpdating").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::Media::Protection::RenewalStatus::AppComponentsMayNeedUpdating)));
	Nan::Set(enumObject, Nan::New<String>("noComponentsFound").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::Media::Protection::RenewalStatus::NoComponentsFound)));
  }



  
  static bool IsProtectionRenewalContractJsObject(Local<Value> value)
  {
    if (!value->IsObject())
    {
      return false;
    }

    Local<String> symbol;
    Local<Object> obj = Nan::To<Object>(value).ToLocalChecked();

    return true;
  }

  ::Windows::Media::Protection::ProtectionRenewalContract ProtectionRenewalContractFromJsObject(Local<Value> value)
  {
    HandleScope scope;
    ::Windows::Media::Protection::ProtectionRenewalContract returnValue;
    
    if (!value->IsObject())
    {
      Nan::ThrowError(Nan::TypeError(NodeRT::Utils::NewString(L"Unexpected type, expected an object")));
      return returnValue;
    }

    Local<Object> obj = Nan::To<Object>(value).ToLocalChecked();
    Local<String> symbol;

    return returnValue;
  }

  Local<Value> ProtectionRenewalContractToJsObject(::Windows::Media::Protection::ProtectionRenewalContract value)
  {
    EscapableHandleScope scope;

    Local<Object> obj = Nan::New<Object>();

    
    return scope.Escape(obj);
  }

  
  class MediaProtectionManager : 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>("MediaProtectionManager").ToLocalChecked());
      localRef->InstanceTemplate()->SetInternalFieldCount(1);
      
                        
      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>("properties").ToLocalChecked(), PropertiesGetter);
      
      Local<Object> constructor = Nan::To<Object>(Nan::GetFunction(localRef).ToLocalChecked()).ToLocalChecked();
	  Nan::SetMethod(constructor, "castFrom", CastFrom);


      Nan::Set(exports, Nan::New<String>("MediaProtectionManager").ToLocalChecked(), constructor);
    }


    virtual ::Platform::Object^ GetObjectInstance() const override
    {
      return _instance;
    }

  private:
    
    MediaProtectionManager(::Windows::Media::Protection::MediaProtectionManager^ 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::Media::Protection::MediaProtectionManager^ winRtInstance;


      if (info.Length() == 1 && OpaqueWrapper::IsOpaqueWrapper(info[0]) &&
        NodeRT::Utils::IsWinRtWrapperOf<::Windows::Media::Protection::MediaProtectionManager^>(info[0]))
      {
        try 
        {
          winRtInstance = (::Windows::Media::Protection::MediaProtectionManager^) NodeRT::Utils::GetObjectInstance(info[0]);
        }
        catch (Platform::Exception ^exception)
        {
          NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
          return;
        }
      }
      else if (info.Length() == 0)
      {
        try
        {
          winRtInstance = ref new ::Windows::Media::Protection::MediaProtectionManager();
        }
        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());

      MediaProtectionManager *wrapperInstance = new MediaProtectionManager(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::Media::Protection::MediaProtectionManager^>(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::Media::Protection::MediaProtectionManager^ winRtInstance;
		try
		{
			winRtInstance = (::Windows::Media::Protection::MediaProtectionManager^) NodeRT::Utils::GetObjectInstance(info[0]);
		}
		catch (Platform::Exception ^exception)
		{
			NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
			return;
		}

		info.GetReturnValue().Set(WrapMediaProtectionManager(winRtInstance));
    }


  



    static void PropertiesGetter(Local<String> property, const Nan::PropertyCallbackInfo<v8::Value> &info)
    {
      HandleScope scope;
      
      if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::Media::Protection::MediaProtectionManager^>(info.This()))
      {
        return;
      }

      MediaProtectionManager *wrapper = MediaProtectionManager::Unwrap<MediaProtectionManager>(info.This());

      try 
      {
        ::Windows::Foundation::Collections::IPropertySet^ result = wrapper->_instance->Properties;
        info.GetReturnValue().Set(NodeRT::Utils::CreateExternalWinRTObject("Windows.Foundation.Collections", "IPropertySet", result));
        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(info[0]);
      auto str = *eventName;
      
      Local<Function> callback = info[1].As<Function>();
      
      ::Windows::Foundation::EventRegistrationToken registrationToken;
      if (NodeRT::Utils::CaseInsenstiveEquals(L"componentLoadFailed", str))
      {
        if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::Media::Protection::MediaProtectionManager^>(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;
        }
        MediaProtectionManager *wrapper = MediaProtectionManager::Unwrap<MediaProtectionManager>(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->ComponentLoadFailed::add(
            ref new ::Windows::Media::Protection::ComponentLoadFailedEventHandler(
            [callbackObjPtr](::Windows::Media::Protection::MediaProtectionManager^ arg0, ::Windows::Media::Protection::ComponentLoadFailedEventArgs^ arg1) {
              NodeUtils::Async::RunOnMain([callbackObjPtr , arg0, arg1]() {
           	    HandleScope scope;
                TryCatch tryCatch;
              
                Local<Value> error;

                Local<Value> wrappedArg0 = WrapMediaProtectionManager(arg0);
                Local<Value> wrappedArg1 = WrapComponentLoadFailedEventArgs(arg1);

                if (tryCatch.HasCaught())
                {
                  error = Nan::To<Object>(tryCatch.Exception()).ToLocalChecked();
                }
                else 
                {
                  error = Undefined();
                }

				// TODO: this is ugly! Needed due to the possibility of expception occuring inside object convertors
				// can be fixed by wrapping the conversion code in a function and calling it on the fly
				// we must clear the try catch block here so the invoked inner method exception won't get swollen (issue #52) 
				tryCatch.~TryCatch();


                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 if (NodeRT::Utils::CaseInsenstiveEquals(L"rebootNeeded", str))
      {
        if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::Media::Protection::MediaProtectionManager^>(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;
        }
        MediaProtectionManager *wrapper = MediaProtectionManager::Unwrap<MediaProtectionManager>(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->RebootNeeded::add(
            ref new ::Windows::Media::Protection::RebootNeededEventHandler(
            [callbackObjPtr](::Windows::Media::Protection::MediaProtectionManager^ arg0) {
              NodeUtils::Async::RunOnMain([callbackObjPtr , arg0]() {
           	    HandleScope scope;
                TryCatch tryCatch;
              
                Local<Value> error;

                Local<Value> wrappedArg0 = WrapMediaProtectionManager(arg0);

                if (tryCatch.HasCaught())
                {
                  error = Nan::To<Object>(tryCatch.Exception()).ToLocalChecked();
                }
                else 
                {
                  error = Undefined();
                }

				// TODO: this is ugly! Needed due to the possibility of expception occuring inside object convertors
				// can be fixed by wrapping the conversion code in a function and calling it on the fly
				// we must clear the try catch block here so the invoked inner method exception won't get swollen (issue #52) 
				tryCatch.~TryCatch();


                if (wrappedArg0.IsEmpty()) wrappedArg0 = Undefined();

                Local<Value> args[] = { wrappedArg0 };
                Local<Object> callbackObjLocalRef = Nan::New<Object>(*callbackObjPtr);
                NodeRT::Utils::CallCallbackInDomain(callbackObjLocalRef, _countof(args), args);
              });
            })
          );
        }
        catch (Platform::Exception ^exception)
        {
          NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
          return;
        }

      }
      else if (NodeRT::Utils::CaseInsenstiveEquals(L"serviceRequested", str))
      {
        if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::Media::Protection::MediaProtectionManager^>(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;
        }
        MediaProtectionManager *wrapper = MediaProtectionManager::Unwrap<MediaProtectionManager>(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->ServiceRequested::add(
            ref new ::Windows::Media::Protection::ServiceRequestedEventHandler(
            [callbackObjPtr](::Windows::Media::Protection::MediaProtectionManager^ arg0, ::Windows::Media::Protection::ServiceRequestedEventArgs^ arg1) {
              NodeUtils::Async::RunOnMain([callbackObjPtr , arg0, arg1]() {
           	    HandleScope scope;
                TryCatch tryCatch;
              
                Local<Value> error;

                Local<Value> wrappedArg0 = WrapMediaProtectionManager(arg0);
                Local<Value> wrappedArg1 = WrapServiceRequestedEventArgs(arg1);

                if (tryCatch.HasCaught())
                {
                  error = Nan::To<Object>(tryCatch.Exception()).ToLocalChecked();
                }
                else 
                {
                  error = Undefined();
                }

				// TODO: this is ugly! Needed due to the possibility of expception occuring inside object convertors
				// can be fixed by wrapping the conversion code in a function and calling it on the fly
				// we must clear the try catch block here so the invoked inner method exception won't get swollen (issue #52) 
				tryCatch.~TryCatch();


                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(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(info[0]);
      auto str = *eventName;

      if ((NodeRT::Utils::CaseInsenstiveEquals(L"componentLoadFailed", str)) &&(NodeRT::Utils::CaseInsenstiveEquals(L"rebootNeeded", str)) &&(NodeRT::Utils::CaseInsenstiveEquals(L"serviceRequested", str)))
      {
        Nan::ThrowError(Nan::Error(String::Concat(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"componentLoadFailed", str))
        {
          if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::Media::Protection::MediaProtectionManager^>(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;
          }
          MediaProtectionManager *wrapper = MediaProtectionManager::Unwrap<MediaProtectionManager>(info.This());
          wrapper->_instance->ComponentLoadFailed::remove(registrationToken);
        }
        else if (NodeRT::Utils::CaseInsenstiveEquals(L"rebootNeeded", str))
        {
          if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::Media::Protection::MediaProtectionManager^>(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;
          }
          MediaProtectionManager *wrapper = MediaProtectionManager::Unwrap<MediaProtectionManager>(info.This());
          wrapper->_instance->RebootNeeded::remove(registrationToken);
        }
        else if (NodeRT::Utils::CaseInsenstiveEquals(L"serviceRequested", str))
        {
          if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::Media::Protection::MediaProtectionManager^>(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;
          }
          MediaProtectionManager *wrapper = MediaProtectionManager::Unwrap<MediaProtectionManager>(info.This());
          wrapper->_instance->ServiceRequested::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::Media::Protection::MediaProtectionManager^ _instance;
    static Persistent<FunctionTemplate> s_constructorTemplate;

    friend v8::Local<v8::Value> WrapMediaProtectionManager(::Windows::Media::Protection::MediaProtectionManager^ wintRtInstance);
    friend ::Windows::Media::Protection::MediaProtectionManager^ UnwrapMediaProtectionManager(Local<Value> value);
  };
  Persistent<FunctionTemplate> MediaProtectionManager::s_constructorTemplate;

  v8::Local<v8::Value> WrapMediaProtectionManager(::Windows::Media::Protection::MediaProtectionManager^ 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>(MediaProtectionManager::s_constructorTemplate);
    return scope.Escape(Nan::NewInstance(Nan::GetFunction(localRef).ToLocalChecked(),_countof(args), args).ToLocalChecked());
  }

  ::Windows::Media::Protection::MediaProtectionManager^ UnwrapMediaProtectionManager(Local<Value> value)
  {
     return MediaProtectionManager::Unwrap<MediaProtectionManager>(Nan::To<Object>(value).ToLocalChecked())->_instance;
  }

  void InitMediaProtectionManager(Local<Object> exports)
  {
    MediaProtectionManager::Init(exports);
  }

  class ServiceRequestedEventArgs : 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>("ServiceRequestedEventArgs").ToLocalChecked());
      localRef->InstanceTemplate()->SetInternalFieldCount(1);
      
                              
      Nan::SetAccessor(localRef->PrototypeTemplate(), Nan::New<String>("completion").ToLocalChecked(), CompletionGetter);
      Nan::SetAccessor(localRef->PrototypeTemplate(), Nan::New<String>("request").ToLocalChecked(), RequestGetter);
      Nan::SetAccessor(localRef->PrototypeTemplate(), Nan::New<String>("mediaPlaybackItem").ToLocalChecked(), MediaPlaybackItemGetter);
      
      Local<Object> constructor = Nan::To<Object>(Nan::GetFunction(localRef).ToLocalChecked()).ToLocalChecked();
	  Nan::SetMethod(constructor, "castFrom", CastFrom);


      Nan::Set(exports, Nan::New<String>("ServiceRequestedEventArgs").ToLocalChecked(), constructor);
    }


    virtual ::Platform::Object^ GetObjectInstance() const override
    {
      return _instance;
    }

  private:
    
    ServiceRequestedEventArgs(::Windows::Media::Protection::ServiceRequestedEventArgs^ 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::Media::Protection::ServiceRequestedEventArgs^ winRtInstance;


      if (info.Length() == 1 && OpaqueWrapper::IsOpaqueWrapper(info[0]) &&
        NodeRT::Utils::IsWinRtWrapperOf<::Windows::Media::Protection::ServiceRequestedEventArgs^>(info[0]))
      {
        try 
        {
          winRtInstance = (::Windows::Media::Protection::ServiceRequestedEventArgs^) 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());

      ServiceRequestedEventArgs *wrapperInstance = new ServiceRequestedEventArgs(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::Media::Protection::ServiceRequestedEventArgs^>(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::Media::Protection::ServiceRequestedEventArgs^ winRtInstance;
		try
		{
			winRtInstance = (::Windows::Media::Protection::ServiceRequestedEventArgs^) NodeRT::Utils::GetObjectInstance(info[0]);
		}
		catch (Platform::Exception ^exception)
		{
			NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
			return;
		}

		info.GetReturnValue().Set(WrapServiceRequestedEventArgs(winRtInstance));
    }


  



    static void CompletionGetter(Local<String> property, const Nan::PropertyCallbackInfo<v8::Value> &info)
    {
      HandleScope scope;
      
      if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::Media::Protection::ServiceRequestedEventArgs^>(info.This()))
      {
        return;
      }

      ServiceRequestedEventArgs *wrapper = ServiceRequestedEventArgs::Unwrap<ServiceRequestedEventArgs>(info.This());

      try 
      {
        ::Windows::Media::Protection::MediaProtectionServiceCompletion^ result = wrapper->_instance->Completion;
        info.GetReturnValue().Set(WrapMediaProtectionServiceCompletion(result));
        return;
      }
      catch (Platform::Exception ^exception)
      {
        NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
        return;
      }
    }
    
    static void RequestGetter(Local<String> property, const Nan::PropertyCallbackInfo<v8::Value> &info)
    {
      HandleScope scope;
      
      if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::Media::Protection::ServiceRequestedEventArgs^>(info.This()))
      {
        return;
      }

      ServiceRequestedEventArgs *wrapper = ServiceRequestedEventArgs::Unwrap<ServiceRequestedEventArgs>(info.This());

      try 
      {
        ::Windows::Media::Protection::IMediaProtectionServiceRequest^ result = wrapper->_instance->Request;
        info.GetReturnValue().Set(WrapIMediaProtectionServiceRequest(result));
        return;
      }
      catch (Platform::Exception ^exception)
      {
        NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
        return;
      }
    }
    
    static void MediaPlaybackItemGetter(Local<String> property, const Nan::PropertyCallbackInfo<v8::Value> &info)
    {
      HandleScope scope;
      
      if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::Media::Protection::ServiceRequestedEventArgs^>(info.This()))
      {
        return;
      }

      ServiceRequestedEventArgs *wrapper = ServiceRequestedEventArgs::Unwrap<ServiceRequestedEventArgs>(info.This());

      try 
      {
        ::Windows::Media::Playback::MediaPlaybackItem^ result = wrapper->_instance->MediaPlaybackItem;
        info.GetReturnValue().Set(NodeRT::Utils::CreateExternalWinRTObject("Windows.Media.Playback", "MediaPlaybackItem", result));
        return;
      }
      catch (Platform::Exception ^exception)
      {
        NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
        return;
      }
    }
    


  private:
    ::Windows::Media::Protection::ServiceRequestedEventArgs^ _instance;
    static Persistent<FunctionTemplate> s_constructorTemplate;

    friend v8::Local<v8::Value> WrapServiceRequestedEventArgs(::Windows::Media::Protection::ServiceRequestedEventArgs^ wintRtInstance);
    friend ::Windows::Media::Protection::ServiceRequestedEventArgs^ UnwrapServiceRequestedEventArgs(Local<Value> value);
  };
  Persistent<FunctionTemplate> ServiceRequestedEventArgs::s_constructorTemplate;

  v8::Local<v8::Value> WrapServiceRequestedEventArgs(::Windows::Media::Protection::ServiceRequestedEventArgs^ 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>(ServiceRequestedEventArgs::s_constructorTemplate);
    return scope.Escape(Nan::NewInstance(Nan::GetFunction(localRef).ToLocalChecked(),_countof(args), args).ToLocalChecked());
  }

  ::Windows::Media::Protection::ServiceRequestedEventArgs^ UnwrapServiceRequestedEventArgs(Local<Value> value)
  {
     return ServiceRequestedEventArgs::Unwrap<ServiceRequestedEventArgs>(Nan::To<Object>(value).ToLocalChecked())->_instance;
  }

  void InitServiceRequestedEventArgs(Local<Object> exports)
  {
    ServiceRequestedEventArgs::Init(exports);
  }

  class ComponentLoadFailedEventArgs : 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>("ComponentLoadFailedEventArgs").ToLocalChecked());
      localRef->InstanceTemplate()->SetInternalFieldCount(1);
      
                              
      Nan::SetAccessor(localRef->PrototypeTemplate(), Nan::New<String>("completion").ToLocalChecked(), CompletionGetter);
      Nan::SetAccessor(localRef->PrototypeTemplate(), Nan::New<String>("information").ToLocalChecked(), InformationGetter);
      
      Local<Object> constructor = Nan::To<Object>(Nan::GetFunction(localRef).ToLocalChecked()).ToLocalChecked();
	  Nan::SetMethod(constructor, "castFrom", CastFrom);


      Nan::Set(exports, Nan::New<String>("ComponentLoadFailedEventArgs").ToLocalChecked(), constructor);
    }


    virtual ::Platform::Object^ GetObjectInstance() const override
    {
      return _instance;
    }

  private:
    
    ComponentLoadFailedEventArgs(::Windows::Media::Protection::ComponentLoadFailedEventArgs^ 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::Media::Protection::ComponentLoadFailedEventArgs^ winRtInstance;


      if (info.Length() == 1 && OpaqueWrapper::IsOpaqueWrapper(info[0]) &&
        NodeRT::Utils::IsWinRtWrapperOf<::Windows::Media::Protection::ComponentLoadFailedEventArgs^>(info[0]))
      {
        try 
        {
          winRtInstance = (::Windows::Media::Protection::ComponentLoadFailedEventArgs^) 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());

      ComponentLoadFailedEventArgs *wrapperInstance = new ComponentLoadFailedEventArgs(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::Media::Protection::ComponentLoadFailedEventArgs^>(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::Media::Protection::ComponentLoadFailedEventArgs^ winRtInstance;
		try
		{
			winRtInstance = (::Windows::Media::Protection::ComponentLoadFailedEventArgs^) NodeRT::Utils::GetObjectInstance(info[0]);
		}
		catch (Platform::Exception ^exception)
		{
			NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
			return;
		}

		info.GetReturnValue().Set(WrapComponentLoadFailedEventArgs(winRtInstance));
    }


  



    static void CompletionGetter(Local<String> property, const Nan::PropertyCallbackInfo<v8::Value> &info)
    {
      HandleScope scope;
      
      if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::Media::Protection::ComponentLoadFailedEventArgs^>(info.This()))
      {
        return;
      }

      ComponentLoadFailedEventArgs *wrapper = ComponentLoadFailedEventArgs::Unwrap<ComponentLoadFailedEventArgs>(info.This());

      try 
      {
        ::Windows::Media::Protection::MediaProtectionServiceCompletion^ result = wrapper->_instance->Completion;
        info.GetReturnValue().Set(WrapMediaProtectionServiceCompletion(result));
        return;
      }
      catch (Platform::Exception ^exception)
      {
        NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
        return;
      }
    }
    
    static void InformationGetter(Local<String> property, const Nan::PropertyCallbackInfo<v8::Value> &info)
    {
      HandleScope scope;
      
      if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::Media::Protection::ComponentLoadFailedEventArgs^>(info.This()))
      {
        return;
      }

      ComponentLoadFailedEventArgs *wrapper = ComponentLoadFailedEventArgs::Unwrap<ComponentLoadFailedEventArgs>(info.This());

      try 
      {
        ::Windows::Media::Protection::RevocationAndRenewalInformation^ result = wrapper->_instance->Information;
        info.GetReturnValue().Set(WrapRevocationAndRenewalInformation(result));
        return;
      }
      catch (Platform::Exception ^exception)
      {
        NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
        return;
      }
    }
    


  private:
    ::Windows::Media::Protection::ComponentLoadFailedEventArgs^ _instance;
    static Persistent<FunctionTemplate> s_constructorTemplate;

    friend v8::Local<v8::Value> WrapComponentLoadFailedEventArgs(::Windows::Media::Protection::ComponentLoadFailedEventArgs^ wintRtInstance);
    friend ::Windows::Media::Protection::ComponentLoadFailedEventArgs^ UnwrapComponentLoadFailedEventArgs(Local<Value> value);
  };
  Persistent<FunctionTemplate> ComponentLoadFailedEventArgs::s_constructorTemplate;

  v8::Local<v8::Value> WrapComponentLoadFailedEventArgs(::Windows::Media::Protection::ComponentLoadFailedEventArgs^ 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>(ComponentLoadFailedEventArgs::s_constructorTemplate);
    return scope.Escape(Nan::NewInstance(Nan::GetFunction(localRef).ToLocalChecked(),_countof(args), args).ToLocalChecked());
  }

  ::Windows::Media::Protection::ComponentLoadFailedEventArgs^ UnwrapComponentLoadFailedEventArgs(Local<Value> value)
  {
     return ComponentLoadFailedEventArgs::Unwrap<ComponentLoadFailedEventArgs>(Nan::To<Object>(value).ToLocalChecked())->_instance;
  }

  void InitComponentLoadFailedEventArgs(Local<Object> exports)
  {
    ComponentLoadFailedEventArgs::Init(exports);
  }

  class MediaProtectionServiceCompletion : 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>("MediaProtectionServiceCompletion").ToLocalChecked());
      localRef->InstanceTemplate()->SetInternalFieldCount(1);
      
            
      Nan::SetPrototypeMethod(localRef, "complete", Complete);
      
                        
      Local<Object> constructor = Nan::To<Object>(Nan::GetFunction(localRef).ToLocalChecked()).ToLocalChecked();
	  Nan::SetMethod(constructor, "castFrom", CastFrom);


      Nan::Set(exports, Nan::New<String>("MediaProtectionServiceCompletion").ToLocalChecked(), constructor);
    }


    virtual ::Platform::Object^ GetObjectInstance() const override
    {
      return _instance;
    }

  private:
    
    MediaProtectionServiceCompletion(::Windows::Media::Protection::MediaProtectionServiceCompletion^ 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::Media::Protection::MediaProtectionServiceCompletion^ winRtInstance;


      if (info.Length() == 1 && OpaqueWrapper::IsOpaqueWrapper(info[0]) &&
        NodeRT::Utils::IsWinRtWrapperOf<::Windows::Media::Protection::MediaProtectionServiceCompletion^>(info[0]))
      {
        try 
        {
          winRtInstance = (::Windows::Media::Protection::MediaProtectionServiceCompletion^) 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());

      MediaProtectionServiceCompletion *wrapperInstance = new MediaProtectionServiceCompletion(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::Media::Protection::MediaProtectionServiceCompletion^>(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::Media::Protection::MediaProtectionServiceCompletion^ winRtInstance;
		try
		{
			winRtInstance = (::Windows::Media::Protection::MediaProtectionServiceCompletion^) NodeRT::Utils::GetObjectInstance(info[0]);
		}
		catch (Platform::Exception ^exception)
		{
			NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
			return;
		}

		info.GetReturnValue().Set(WrapMediaProtectionServiceCompletion(winRtInstance));
    }


  
    static void Complete(Nan::NAN_METHOD_ARGS_TYPE info)
    {
      HandleScope scope;

      if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::Media::Protection::MediaProtectionServiceCompletion^>(info.This()))
      {
        return;
      }

      MediaProtectionServiceCompletion *wrapper = MediaProtectionServiceCompletion::Unwrap<MediaProtectionServiceCompletion>(info.This());

      if (info.Length() == 1
        && info[0]->IsBoolean())
      {
        try
        {
          bool arg0 = Nan::To<bool>(info[0]).FromMaybe(false);
          
          wrapper->_instance->Complete(arg0);
          return;   
        }
        catch (Platform::Exception ^exception)
        {
          NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
          return;
        }
      }
      else 
      {
        Nan::ThrowError(Nan::Error(NodeRT::Utils::NewString(L"Bad arguments: no suitable overload found")));
        return;
      }
    }





  private:
    ::Windows::Media::Protection::MediaProtectionServiceCompletion^ _instance;
    static Persistent<FunctionTemplate> s_constructorTemplate;

    friend v8::Local<v8::Value> WrapMediaProtectionServiceCompletion(::Windows::Media::Protection::MediaProtectionServiceCompletion^ wintRtInstance);
    friend ::Windows::Media::Protection::MediaProtectionServiceCompletion^ UnwrapMediaProtectionServiceCompletion(Local<Value> value);
  };
  Persistent<FunctionTemplate> MediaProtectionServiceCompletion::s_constructorTemplate;

  v8::Local<v8::Value> WrapMediaProtectionServiceCompletion(::Windows::Media::Protection::MediaProtectionServiceCompletion^ 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>(MediaProtectionServiceCompletion::s_constructorTemplate);
    return scope.Escape(Nan::NewInstance(Nan::GetFunction(localRef).ToLocalChecked(),_countof(args), args).ToLocalChecked());
  }

  ::Windows::Media::Protection::MediaProtectionServiceCompletion^ UnwrapMediaProtectionServiceCompletion(Local<Value> value)
  {
     return MediaProtectionServiceCompletion::Unwrap<MediaProtectionServiceCompletion>(Nan::To<Object>(value).ToLocalChecked())->_instance;
  }

  void InitMediaProtectionServiceCompletion(Local<Object> exports)
  {
    MediaProtectionServiceCompletion::Init(exports);
  }

  class RevocationAndRenewalInformation : 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>("RevocationAndRenewalInformation").ToLocalChecked());
      localRef->InstanceTemplate()->SetInternalFieldCount(1);
      
                              
      Nan::SetAccessor(localRef->PrototypeTemplate(), Nan::New<String>("items").ToLocalChecked(), ItemsGetter);
      
      Local<Object> constructor = Nan::To<Object>(Nan::GetFunction(localRef).ToLocalChecked()).ToLocalChecked();
	  Nan::SetMethod(constructor, "castFrom", CastFrom);


      Nan::Set(exports, Nan::New<String>("RevocationAndRenewalInformation").ToLocalChecked(), constructor);
    }


    virtual ::Platform::Object^ GetObjectInstance() const override
    {
      return _instance;
    }

  private:
    
    RevocationAndRenewalInformation(::Windows::Media::Protection::RevocationAndRenewalInformation^ 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::Media::Protection::RevocationAndRenewalInformation^ winRtInstance;


      if (info.Length() == 1 && OpaqueWrapper::IsOpaqueWrapper(info[0]) &&
        NodeRT::Utils::IsWinRtWrapperOf<::Windows::Media::Protection::RevocationAndRenewalInformation^>(info[0]))
      {
        try 
        {
          winRtInstance = (::Windows::Media::Protection::RevocationAndRenewalInformation^) 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());

      RevocationAndRenewalInformation *wrapperInstance = new RevocationAndRenewalInformation(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::Media::Protection::RevocationAndRenewalInformation^>(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::Media::Protection::RevocationAndRenewalInformation^ winRtInstance;
		try
		{
			winRtInstance = (::Windows::Media::Protection::RevocationAndRenewalInformation^) NodeRT::Utils::GetObjectInstance(info[0]);
		}
		catch (Platform::Exception ^exception)
		{
			NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
			return;
		}

		info.GetReturnValue().Set(WrapRevocationAndRenewalInformation(winRtInstance));
    }


  



    static void ItemsGetter(Local<String> property, const Nan::PropertyCallbackInfo<v8::Value> &info)
    {
      HandleScope scope;
      
      if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::Media::Protection::RevocationAndRenewalInformation^>(info.This()))
      {
        return;
      }

      RevocationAndRenewalInformation *wrapper = RevocationAndRenewalInformation::Unwrap<RevocationAndRenewalInformation>(info.This());

      try 
      {
        ::Windows::Foundation::Collections::IVector<::Windows::Media::Protection::RevocationAndRenewalItem^>^ result = wrapper->_instance->Items;
        info.GetReturnValue().Set(NodeRT::Collections::VectorWrapper<::Windows::Media::Protection::RevocationAndRenewalItem^>::CreateVectorWrapper(result, 
            [](::Windows::Media::Protection::RevocationAndRenewalItem^ val) -> Local<Value> {
              return WrapRevocationAndRenewalItem(val);
            },
            [](Local<Value> value) -> bool {
              return NodeRT::Utils::IsWinRtWrapperOf<::Windows::Media::Protection::RevocationAndRenewalItem^>(value);
            },
            [](Local<Value> value) -> ::Windows::Media::Protection::RevocationAndRenewalItem^ {
              return UnwrapRevocationAndRenewalItem(value);
            }
          ));
        return;
      }
      catch (Platform::Exception ^exception)
      {
        NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
        return;
      }
    }
    


  private:
    ::Windows::Media::Protection::RevocationAndRenewalInformation^ _instance;
    static Persistent<FunctionTemplate> s_constructorTemplate;

    friend v8::Local<v8::Value> WrapRevocationAndRenewalInformation(::Windows::Media::Protection::RevocationAndRenewalInformation^ wintRtInstance);
    friend ::Windows::Media::Protection::RevocationAndRenewalInformation^ UnwrapRevocationAndRenewalInformation(Local<Value> value);
  };
  Persistent<FunctionTemplate> RevocationAndRenewalInformation::s_constructorTemplate;

  v8::Local<v8::Value> WrapRevocationAndRenewalInformation(::Windows::Media::Protection::RevocationAndRenewalInformation^ 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>(RevocationAndRenewalInformation::s_constructorTemplate);
    return scope.Escape(Nan::NewInstance(Nan::GetFunction(localRef).ToLocalChecked(),_countof(args), args).ToLocalChecked());
  }

  ::Windows::Media::Protection::RevocationAndRenewalInformation^ UnwrapRevocationAndRenewalInformation(Local<Value> value)
  {
     return RevocationAndRenewalInformation::Unwrap<RevocationAndRenewalInformation>(Nan::To<Object>(value).ToLocalChecked())->_instance;
  }

  void InitRevocationAndRenewalInformation(Local<Object> exports)
  {
    RevocationAndRenewalInformation::Init(exports);
  }

  class RevocationAndRenewalItem : 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>("RevocationAndRenewalItem").ToLocalChecked());
      localRef->InstanceTemplate()->SetInternalFieldCount(1);
      
                              
      Nan::SetAccessor(localRef->PrototypeTemplate(), Nan::New<String>("headerHash").ToLocalChecked(), HeaderHashGetter);
      Nan::SetAccessor(localRef->PrototypeTemplate(), Nan::New<String>("name").ToLocalChecked(), NameGetter);
      Nan::SetAccessor(localRef->PrototypeTemplate(), Nan::New<String>("publicKeyHash").ToLocalChecked(), PublicKeyHashGetter);
      Nan::SetAccessor(localRef->PrototypeTemplate(), Nan::New<String>("reasons").ToLocalChecked(), ReasonsGetter);
      Nan::SetAccessor(localRef->PrototypeTemplate(), Nan::New<String>("renewalId").ToLocalChecked(), RenewalIdGetter);
      
      Local<Object> constructor = Nan::To<Object>(Nan::GetFunction(localRef).ToLocalChecked()).ToLocalChecked();
	  Nan::SetMethod(constructor, "castFrom", CastFrom);


      Nan::Set(exports, Nan::New<String>("RevocationAndRenewalItem").ToLocalChecked(), constructor);
    }


    virtual ::Platform::Object^ GetObjectInstance() const override
    {
      return _instance;
    }

  private:
    
    RevocationAndRenewalItem(::Windows::Media::Protection::RevocationAndRenewalItem^ 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::Media::Protection::RevocationAndRenewalItem^ winRtInstance;


      if (info.Length() == 1 && OpaqueWrapper::IsOpaqueWrapper(info[0]) &&
        NodeRT::Utils::IsWinRtWrapperOf<::Windows::Media::Protection::RevocationAndRenewalItem^>(info[0]))
      {
        try 
        {
          winRtInstance = (::Windows::Media::Protection::RevocationAndRenewalItem^) 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());

      RevocationAndRenewalItem *wrapperInstance = new RevocationAndRenewalItem(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::Media::Protection::RevocationAndRenewalItem^>(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::Media::Protection::RevocationAndRenewalItem^ winRtInstance;
		try
		{
			winRtInstance = (::Windows::Media::Protection::RevocationAndRenewalItem^) NodeRT::Utils::GetObjectInstance(info[0]);
		}
		catch (Platform::Exception ^exception)
		{
			NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
			return;
		}

		info.GetReturnValue().Set(WrapRevocationAndRenewalItem(winRtInstance));
    }


  



    static void HeaderHashGetter(Local<String> property, const Nan::PropertyCallbackInfo<v8::Value> &info)
    {
      HandleScope scope;
      
      if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::Media::Protection::RevocationAndRenewalItem^>(info.This()))
      {
        return;
      }

      RevocationAndRenewalItem *wrapper = RevocationAndRenewalItem::Unwrap<RevocationAndRenewalItem>(info.This());

      try 
      {
        Platform::String^ result = wrapper->_instance->HeaderHash;
        info.GetReturnValue().Set(NodeRT::Utils::NewString(result->Data()));
        return;
      }
      catch (Platform::Exception ^exception)
      {
        NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
        return;
      }
    }
    
    static void NameGetter(Local<String> property, const Nan::PropertyCallbackInfo<v8::Value> &info)
    {
      HandleScope scope;
      
      if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::Media::Protection::RevocationAndRenewalItem^>(info.This()))
      {
        return;
      }

      RevocationAndRenewalItem *wrapper = RevocationAndRenewalItem::Unwrap<RevocationAndRenewalItem>(info.This());

      try 
      {
        Platform::String^ result = wrapper->_instance->Name;
        info.GetReturnValue().Set(NodeRT::Utils::NewString(result->Data()));
        return;
      }
      catch (Platform::Exception ^exception)
      {
        NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
        return;
      }
    }
    
    static void PublicKeyHashGetter(Local<String> property, const Nan::PropertyCallbackInfo<v8::Value> &info)
    {
      HandleScope scope;
      
      if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::Media::Protection::RevocationAndRenewalItem^>(info.This()))
      {
        return;
      }

      RevocationAndRenewalItem *wrapper = RevocationAndRenewalItem::Unwrap<RevocationAndRenewalItem>(info.This());

      try 
      {
        Platform::String^ result = wrapper->_instance->PublicKeyHash;
        info.GetReturnValue().Set(NodeRT::Utils::NewString(result->Data()));
        return;
      }
      catch (Platform::Exception ^exception)
      {
        NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
        return;
      }
    }
    
    static void ReasonsGetter(Local<String> property, const Nan::PropertyCallbackInfo<v8::Value> &info)
    {
      HandleScope scope;
      
      if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::Media::Protection::RevocationAndRenewalItem^>(info.This()))
      {
        return;
      }

      RevocationAndRenewalItem *wrapper = RevocationAndRenewalItem::Unwrap<RevocationAndRenewalItem>(info.This());

      try 
      {
        ::Windows::Media::Protection::RevocationAndRenewalReasons result = wrapper->_instance->Reasons;
        info.GetReturnValue().Set(Nan::New<Integer>(static_cast<int>(result)));
        return;
      }
      catch (Platform::Exception ^exception)
      {
        NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
        return;
      }
    }
    
    static void RenewalIdGetter(Local<String> property, const Nan::PropertyCallbackInfo<v8::Value> &info)
    {
      HandleScope scope;
      
      if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::Media::Protection::RevocationAndRenewalItem^>(info.This()))
      {
        return;
      }

      RevocationAndRenewalItem *wrapper = RevocationAndRenewalItem::Unwrap<RevocationAndRenewalItem>(info.This());

      try 
      {
        Platform::String^ result = wrapper->_instance->RenewalId;
        info.GetReturnValue().Set(NodeRT::Utils::NewString(result->Data()));
        return;
      }
      catch (Platform::Exception ^exception)
      {
        NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
        return;
      }
    }
    


  private:
    ::Windows::Media::Protection::RevocationAndRenewalItem^ _instance;
    static Persistent<FunctionTemplate> s_constructorTemplate;

    friend v8::Local<v8::Value> WrapRevocationAndRenewalItem(::Windows::Media::Protection::RevocationAndRenewalItem^ wintRtInstance);
    friend ::Windows::Media::Protection::RevocationAndRenewalItem^ UnwrapRevocationAndRenewalItem(Local<Value> value);
  };
  Persistent<FunctionTemplate> RevocationAndRenewalItem::s_constructorTemplate;

  v8::Local<v8::Value> WrapRevocationAndRenewalItem(::Windows::Media::Protection::RevocationAndRenewalItem^ 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>(RevocationAndRenewalItem::s_constructorTemplate);
    return scope.Escape(Nan::NewInstance(Nan::GetFunction(localRef).ToLocalChecked(),_countof(args), args).ToLocalChecked());
  }

  ::Windows::Media::Protection::RevocationAndRenewalItem^ UnwrapRevocationAndRenewalItem(Local<Value> value)
  {
     return RevocationAndRenewalItem::Unwrap<RevocationAndRenewalItem>(Nan::To<Object>(value).ToLocalChecked())->_instance;
  }

  void InitRevocationAndRenewalItem(Local<Object> exports)
  {
    RevocationAndRenewalItem::Init(exports);
  }

  class MediaProtectionPMPServer : 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>("MediaProtectionPMPServer").ToLocalChecked());
      localRef->InstanceTemplate()->SetInternalFieldCount(1);
      
                              
      Nan::SetAccessor(localRef->PrototypeTemplate(), Nan::New<String>("properties").ToLocalChecked(), PropertiesGetter);
      
      Local<Object> constructor = Nan::To<Object>(Nan::GetFunction(localRef).ToLocalChecked()).ToLocalChecked();
	  Nan::SetMethod(constructor, "castFrom", CastFrom);


      Nan::Set(exports, Nan::New<String>("MediaProtectionPMPServer").ToLocalChecked(), constructor);
    }


    virtual ::Platform::Object^ GetObjectInstance() const override
    {
      return _instance;
    }

  private:
    
    MediaProtectionPMPServer(::Windows::Media::Protection::MediaProtectionPMPServer^ 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::Media::Protection::MediaProtectionPMPServer^ winRtInstance;


      if (info.Length() == 1 && OpaqueWrapper::IsOpaqueWrapper(info[0]) &&
        NodeRT::Utils::IsWinRtWrapperOf<::Windows::Media::Protection::MediaProtectionPMPServer^>(info[0]))
      {
        try 
        {
          winRtInstance = (::Windows::Media::Protection::MediaProtectionPMPServer^) NodeRT::Utils::GetObjectInstance(info[0]);
        }
        catch (Platform::Exception ^exception)
        {
          NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
          return;
        }
      }
      else if (info.Length() == 1
        && NodeRT::Utils::IsWinRtWrapperOf<::Windows::Foundation::Collections::IPropertySet^>(info[0]))
      {
        try
        {
          ::Windows::Foundation::Collections::IPropertySet^ arg0 = dynamic_cast<::Windows::Foundation::Collections::IPropertySet^>(NodeRT::Utils::GetObjectInstance(info[0]));
          
          winRtInstance = ref new ::Windows::Media::Protection::MediaProtectionPMPServer(arg0);
        }
        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());

      MediaProtectionPMPServer *wrapperInstance = new MediaProtectionPMPServer(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::Media::Protection::MediaProtectionPMPServer^>(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::Media::Protection::MediaProtectionPMPServer^ winRtInstance;
		try
		{
			winRtInstance = (::Windows::Media::Protection::MediaProtectionPMPServer^) NodeRT::Utils::GetObjectInstance(info[0]);
		}
		catch (Platform::Exception ^exception)
		{
			NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
			return;
		}

		info.GetReturnValue().Set(WrapMediaProtectionPMPServer(winRtInstance));
    }


  



    static void PropertiesGetter(Local<String> property, const Nan::PropertyCallbackInfo<v8::Value> &info)
    {
      HandleScope scope;
      
      if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::Media::Protection::MediaProtectionPMPServer^>(info.This()))
      {
        return;
      }

      MediaProtectionPMPServer *wrapper = MediaProtectionPMPServer::Unwrap<MediaProtectionPMPServer>(info.This());

      try 
      {
        ::Windows::Foundation::Collections::IPropertySet^ result = wrapper->_instance->Properties;
        info.GetReturnValue().Set(NodeRT::Utils::CreateExternalWinRTObject("Windows.Foundation.Collections", "IPropertySet", result));
        return;
      }
      catch (Platform::Exception ^exception)
      {
        NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
        return;
      }
    }
    


  private:
    ::Windows::Media::Protection::MediaProtectionPMPServer^ _instance;
    static Persistent<FunctionTemplate> s_constructorTemplate;

    friend v8::Local<v8::Value> WrapMediaProtectionPMPServer(::Windows::Media::Protection::MediaProtectionPMPServer^ wintRtInstance);
    friend ::Windows::Media::Protection::MediaProtectionPMPServer^ UnwrapMediaProtectionPMPServer(Local<Value> value);
  };
  Persistent<FunctionTemplate> MediaProtectionPMPServer::s_constructorTemplate;

  v8::Local<v8::Value> WrapMediaProtectionPMPServer(::Windows::Media::Protection::MediaProtectionPMPServer^ 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>(MediaProtectionPMPServer::s_constructorTemplate);
    return scope.Escape(Nan::NewInstance(Nan::GetFunction(localRef).ToLocalChecked(),_countof(args), args).ToLocalChecked());
  }

  ::Windows::Media::Protection::MediaProtectionPMPServer^ UnwrapMediaProtectionPMPServer(Local<Value> value)
  {
     return MediaProtectionPMPServer::Unwrap<MediaProtectionPMPServer>(Nan::To<Object>(value).ToLocalChecked())->_instance;
  }

  void InitMediaProtectionPMPServer(Local<Object> exports)
  {
    MediaProtectionPMPServer::Init(exports);
  }

  class IMediaProtectionServiceRequest : 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>("IMediaProtectionServiceRequest").ToLocalChecked());
      localRef->InstanceTemplate()->SetInternalFieldCount(1);
      
                              
      Nan::SetAccessor(localRef->PrototypeTemplate(), Nan::New<String>("protectionSystem").ToLocalChecked(), ProtectionSystemGetter);
      Nan::SetAccessor(localRef->PrototypeTemplate(), Nan::New<String>("type").ToLocalChecked(), TypeGetter);
      
      Local<Object> constructor = Nan::To<Object>(Nan::GetFunction(localRef).ToLocalChecked()).ToLocalChecked();
	  Nan::SetMethod(constructor, "castFrom", CastFrom);


      Nan::Set(exports, Nan::New<String>("IMediaProtectionServiceRequest").ToLocalChecked(), constructor);
    }


    virtual ::Platform::Object^ GetObjectInstance() const override
    {
      return _instance;
    }

  private:
    
    IMediaProtectionServiceRequest(::Windows::Media::Protection::IMediaProtectionServiceRequest^ 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::Media::Protection::IMediaProtectionServiceRequest^ winRtInstance;


      if (info.Length() == 1 && OpaqueWrapper::IsOpaqueWrapper(info[0]) &&
        NodeRT::Utils::IsWinRtWrapperOf<::Windows::Media::Protection::IMediaProtectionServiceRequest^>(info[0]))
      {
        try 
        {
          winRtInstance = (::Windows::Media::Protection::IMediaProtectionServiceRequest^) 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());

      IMediaProtectionServiceRequest *wrapperInstance = new IMediaProtectionServiceRequest(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::Media::Protection::IMediaProtectionServiceRequest^>(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::Media::Protection::IMediaProtectionServiceRequest^ winRtInstance;
		try
		{
			winRtInstance = (::Windows::Media::Protection::IMediaProtectionServiceRequest^) NodeRT::Utils::GetObjectInstance(info[0]);
		}
		catch (Platform::Exception ^exception)
		{
			NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
			return;
		}

		info.GetReturnValue().Set(WrapIMediaProtectionServiceRequest(winRtInstance));
    }


  



    static void ProtectionSystemGetter(Local<String> property, const Nan::PropertyCallbackInfo<v8::Value> &info)
    {
      HandleScope scope;
      
      if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::Media::Protection::IMediaProtectionServiceRequest^>(info.This()))
      {
        return;
      }

      IMediaProtectionServiceRequest *wrapper = IMediaProtectionServiceRequest::Unwrap<IMediaProtectionServiceRequest>(info.This());

      try 
      {
        ::Platform::Guid result = wrapper->_instance->ProtectionSystem;
        info.GetReturnValue().Set(NodeRT::Utils::GuidToJs(result));
        return;
      }
      catch (Platform::Exception ^exception)
      {
        NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
        return;
      }
    }
    
    static void TypeGetter(Local<String> property, const Nan::PropertyCallbackInfo<v8::Value> &info)
    {
      HandleScope scope;
      
      if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::Media::Protection::IMediaProtectionServiceRequest^>(info.This()))
      {
        return;
      }

      IMediaProtectionServiceRequest *wrapper = IMediaProtectionServiceRequest::Unwrap<IMediaProtectionServiceRequest>(info.This());

      try 
      {
        ::Platform::Guid result = wrapper->_instance->Type;
        info.GetReturnValue().Set(NodeRT::Utils::GuidToJs(result));
        return;
      }
      catch (Platform::Exception ^exception)
      {
        NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
        return;
      }
    }
    


  private:
    ::Windows::Media::Protection::IMediaProtectionServiceRequest^ _instance;
    static Persistent<FunctionTemplate> s_constructorTemplate;

    friend v8::Local<v8::Value> WrapIMediaProtectionServiceRequest(::Windows::Media::Protection::IMediaProtectionServiceRequest^ wintRtInstance);
    friend ::Windows::Media::Protection::IMediaProtectionServiceRequest^ UnwrapIMediaProtectionServiceRequest(Local<Value> value);
  };
  Persistent<FunctionTemplate> IMediaProtectionServiceRequest::s_constructorTemplate;

  v8::Local<v8::Value> WrapIMediaProtectionServiceRequest(::Windows::Media::Protection::IMediaProtectionServiceRequest^ 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>(IMediaProtectionServiceRequest::s_constructorTemplate);
    return scope.Escape(Nan::NewInstance(Nan::GetFunction(localRef).ToLocalChecked(),_countof(args), args).ToLocalChecked());
  }

  ::Windows::Media::Protection::IMediaProtectionServiceRequest^ UnwrapIMediaProtectionServiceRequest(Local<Value> value)
  {
     return IMediaProtectionServiceRequest::Unwrap<IMediaProtectionServiceRequest>(Nan::To<Object>(value).ToLocalChecked())->_instance;
  }

  void InitIMediaProtectionServiceRequest(Local<Object> exports)
  {
    IMediaProtectionServiceRequest::Init(exports);
  }

  class ProtectionCapabilities : 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>("ProtectionCapabilities").ToLocalChecked());
      localRef->InstanceTemplate()->SetInternalFieldCount(1);
      
            
      Nan::SetPrototypeMethod(localRef, "isTypeSupported", IsTypeSupported);
      
                        
      Local<Object> constructor = Nan::To<Object>(Nan::GetFunction(localRef).ToLocalChecked()).ToLocalChecked();
	  Nan::SetMethod(constructor, "castFrom", CastFrom);


      Nan::Set(exports, Nan::New<String>("ProtectionCapabilities").ToLocalChecked(), constructor);
    }


    virtual ::Platform::Object^ GetObjectInstance() const override
    {
      return _instance;
    }

  private:
    
    ProtectionCapabilities(::Windows::Media::Protection::ProtectionCapabilities^ 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::Media::Protection::ProtectionCapabilities^ winRtInstance;


      if (info.Length() == 1 && OpaqueWrapper::IsOpaqueWrapper(info[0]) &&
        NodeRT::Utils::IsWinRtWrapperOf<::Windows::Media::Protection::ProtectionCapabilities^>(info[0]))
      {
        try 
        {
          winRtInstance = (::Windows::Media::Protection::ProtectionCapabilities^) 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());

      ProtectionCapabilities *wrapperInstance = new ProtectionCapabilities(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::Media::Protection::ProtectionCapabilities^>(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::Media::Protection::ProtectionCapabilities^ winRtInstance;
		try
		{
			winRtInstance = (::Windows::Media::Protection::ProtectionCapabilities^) NodeRT::Utils::GetObjectInstance(info[0]);
		}
		catch (Platform::Exception ^exception)
		{
			NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
			return;
		}

		info.GetReturnValue().Set(WrapProtectionCapabilities(winRtInstance));
    }


  
    static void IsTypeSupported(Nan::NAN_METHOD_ARGS_TYPE info)
    {
      HandleScope scope;

      if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::Media::Protection::ProtectionCapabilities^>(info.This()))
      {
        return;
      }

      ProtectionCapabilities *wrapper = ProtectionCapabilities::Unwrap<ProtectionCapabilities>(info.This());

      if (info.Length() == 2
        && info[0]->IsString()
        && info[1]->IsString())
      {
        try
        {
          Platform::String^ arg0 = ref new Platform::String(NodeRT::Utils::StringToWchar(v8::String::Value(info[0])));
          Platform::String^ arg1 = ref new Platform::String(NodeRT::Utils::StringToWchar(v8::String::Value(info[1])));
          
          ::Windows::Media::Protection::ProtectionCapabilityResult result;
          result = wrapper->_instance->IsTypeSupported(arg0, arg1);
          info.GetReturnValue().Set(Nan::New<Integer>(static_cast<int>(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::Media::Protection::ProtectionCapabilities^ _instance;
    static Persistent<FunctionTemplate> s_constructorTemplate;

    friend v8::Local<v8::Value> WrapProtectionCapabilities(::Windows::Media::Protection::ProtectionCapabilities^ wintRtInstance);
    friend ::Windows::Media::Protection::ProtectionCapabilities^ UnwrapProtectionCapabilities(Local<Value> value);
  };
  Persistent<FunctionTemplate> ProtectionCapabilities::s_constructorTemplate;

  v8::Local<v8::Value> WrapProtectionCapabilities(::Windows::Media::Protection::ProtectionCapabilities^ 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>(ProtectionCapabilities::s_constructorTemplate);
    return scope.Escape(Nan::NewInstance(Nan::GetFunction(localRef).ToLocalChecked(),_countof(args), args).ToLocalChecked());
  }

  ::Windows::Media::Protection::ProtectionCapabilities^ UnwrapProtectionCapabilities(Local<Value> value)
  {
     return ProtectionCapabilities::Unwrap<ProtectionCapabilities>(Nan::To<Object>(value).ToLocalChecked())->_instance;
  }

  void InitProtectionCapabilities(Local<Object> exports)
  {
    ProtectionCapabilities::Init(exports);
  }

  class ComponentRenewal : 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>("ComponentRenewal").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);

      func = Nan::GetFunction(Nan::New<FunctionTemplate>(RenewSystemComponentsAsync)).ToLocalChecked();
      Nan::Set(constructor, Nan::New<String>("renewSystemComponentsAsync").ToLocalChecked(), func);

      Nan::Set(exports, Nan::New<String>("ComponentRenewal").ToLocalChecked(), constructor);
    }


    virtual ::Platform::Object^ GetObjectInstance() const override
    {
      return _instance;
    }

  private:
    
    ComponentRenewal(::Windows::Media::Protection::ComponentRenewal^ 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::Media::Protection::ComponentRenewal^ winRtInstance;


      if (info.Length() == 1 && OpaqueWrapper::IsOpaqueWrapper(info[0]) &&
        NodeRT::Utils::IsWinRtWrapperOf<::Windows::Media::Protection::ComponentRenewal^>(info[0]))
      {
        try 
        {
          winRtInstance = (::Windows::Media::Protection::ComponentRenewal^) 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());

      ComponentRenewal *wrapperInstance = new ComponentRenewal(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::Media::Protection::ComponentRenewal^>(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::Media::Protection::ComponentRenewal^ winRtInstance;
		try
		{
			winRtInstance = (::Windows::Media::Protection::ComponentRenewal^) NodeRT::Utils::GetObjectInstance(info[0]);
		}
		catch (Platform::Exception ^exception)
		{
			NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
			return;
		}

		info.GetReturnValue().Set(WrapComponentRenewal(winRtInstance));
    }


  

    static void RenewSystemComponentsAsync(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::IAsyncOperationWithProgress<::Windows::Media::Protection::RenewalStatus, unsigned int>^ op;
      

      if (info.Length() == 2
        && NodeRT::Utils::IsWinRtWrapperOf<::Windows::Media::Protection::RevocationAndRenewalInformation^>(info[0]))
      {
        try
        {
          ::Windows::Media::Protection::RevocationAndRenewalInformation^ arg0 = UnwrapRevocationAndRenewalInformation(info[0]);
          
          op = ::Windows::Media::Protection::ComponentRenewal::RenewSystemComponentsAsync(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::Media::Protection::RenewalStatus> t) 
      {	
        try
        {
          auto result = t.get();
          NodeUtils::Async::RunCallbackOnMain(asyncToken, [result](NodeUtils::InvokeCallbackDelegate invokeCallback) {

            
            TryCatch tryCatch;
            Local<Value> error; 
            Local<Value> 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};
			// TODO: this is ugly! Needed due to the possibility of expception occuring inside object convertors
			// can be fixed by wrapping the conversion code in a function and calling it on the fly
			// we must clear the try catch block here so the invoked inner method exception won't get swollen (issue #52) 
			tryCatch.~TryCatch();

	  	    
            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);
          });
        }  		
      });
    }




  private:
    ::Windows::Media::Protection::ComponentRenewal^ _instance;
    static Persistent<FunctionTemplate> s_constructorTemplate;

    friend v8::Local<v8::Value> WrapComponentRenewal(::Windows::Media::Protection::ComponentRenewal^ wintRtInstance);
    friend ::Windows::Media::Protection::ComponentRenewal^ UnwrapComponentRenewal(Local<Value> value);
  };
  Persistent<FunctionTemplate> ComponentRenewal::s_constructorTemplate;

  v8::Local<v8::Value> WrapComponentRenewal(::Windows::Media::Protection::ComponentRenewal^ 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>(ComponentRenewal::s_constructorTemplate);
    return scope.Escape(Nan::NewInstance(Nan::GetFunction(localRef).ToLocalChecked(),_countof(args), args).ToLocalChecked());
  }

  ::Windows::Media::Protection::ComponentRenewal^ UnwrapComponentRenewal(Local<Value> value)
  {
     return ComponentRenewal::Unwrap<ComponentRenewal>(Nan::To<Object>(value).ToLocalChecked())->_instance;
  }

  void InitComponentRenewal(Local<Object> exports)
  {
    ComponentRenewal::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::Media::Protection::InitRevocationAndRenewalReasonsEnum(target);
  NodeRT::Windows::Media::Protection::InitGraphicsTrustStatusEnum(target);
  NodeRT::Windows::Media::Protection::InitProtectionCapabilityResultEnum(target);
  NodeRT::Windows::Media::Protection::InitRenewalStatusEnum(target);
  NodeRT::Windows::Media::Protection::InitMediaProtectionManager(target);
  NodeRT::Windows::Media::Protection::InitServiceRequestedEventArgs(target);
  NodeRT::Windows::Media::Protection::InitComponentLoadFailedEventArgs(target);
  NodeRT::Windows::Media::Protection::InitMediaProtectionServiceCompletion(target);
  NodeRT::Windows::Media::Protection::InitRevocationAndRenewalInformation(target);
  NodeRT::Windows::Media::Protection::InitRevocationAndRenewalItem(target);
  NodeRT::Windows::Media::Protection::InitMediaProtectionPMPServer(target);
  NodeRT::Windows::Media::Protection::InitIMediaProtectionServiceRequest(target);
  NodeRT::Windows::Media::Protection::InitProtectionCapabilities(target);
  NodeRT::Windows::Media::Protection::InitComponentRenewal(target);

  NodeRT::Utils::RegisterNameSpace("Windows.Media.Protection", target);
}


NODE_MODULE(binding, init)