// Copyright (c) The NodeRT Contributors
// All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the ""License""); you may
// not use this file except in compliance with the License. You may obtain a
// copy of the License at http://www.apache.org/licenses/LICENSE-2.0
//
// THIS CODE IS PROVIDED ON AN  *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS
// OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY
// IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
// MERCHANTABLITY OR NON-INFRINGEMENT.
//
// See the Apache Version 2.0 License for specific language governing permissions
// and limitations under the License.

// TODO: Verify that this is is still needed..
#define NTDDI_VERSION 0x06010000

#include <v8.h>
#include "nan.h"
#include <string>
#include <ppltasks.h>
#include "CollectionsConverter.h"
#include "CollectionsWrap.h"
#include "node-async.h"
#include "NodeRtUtils.h"
#include "OpaqueWrapper.h"
#include "WrapperBase.h"

#using <Windows.WinMD>

// this undefs fixes the issues of compiling Windows.Data.Json, Windows.Storag.FileProperties, and Windows.Stroage.Search
// Some of the node header files brings windows definitions with the same names as some of the WinRT methods
#undef DocumentProperties
#undef GetObject
#undef CreateEvent
#undef FindText
#undef SendMessage

const char* REGISTRATION_TOKEN_MAP_PROPERTY_NAME = "__registrationTokenMap__";

using v8::Array;
using v8::String;
using v8::Value;
using v8::Boolean;
using v8::Integer;
using v8::FunctionTemplate;
using v8::Object;
using v8::Local;
using v8::Function;
using v8::Date;
using v8::Number;
using v8::PropertyAttribute;
using v8::Primitive;
using Nan::HandleScope;
using Nan::Persistent;
using Nan::Undefined;
using Nan::True;
using Nan::False;
using Nan::Null;
using Nan::MaybeLocal;
using Nan::EscapableHandleScope;
using Nan::HandleScope;
using Nan::TryCatch;
using namespace concurrency;

namespace NodeRT { namespace Windows { namespace Phone { namespace Management { namespace Deployment { 
  v8::Local<v8::Value> WrapEnterprise(::Windows::Phone::Management::Deployment::Enterprise^ wintRtInstance);
  ::Windows::Phone::Management::Deployment::Enterprise^ UnwrapEnterprise(Local<Value> value);
  
  v8::Local<v8::Value> WrapEnterpriseEnrollmentManager(::Windows::Phone::Management::Deployment::EnterpriseEnrollmentManager^ wintRtInstance);
  ::Windows::Phone::Management::Deployment::EnterpriseEnrollmentManager^ UnwrapEnterpriseEnrollmentManager(Local<Value> value);
  
  v8::Local<v8::Value> WrapEnterpriseEnrollmentResult(::Windows::Phone::Management::Deployment::EnterpriseEnrollmentResult^ wintRtInstance);
  ::Windows::Phone::Management::Deployment::EnterpriseEnrollmentResult^ UnwrapEnterpriseEnrollmentResult(Local<Value> value);
  
  v8::Local<v8::Value> WrapInstallationManager(::Windows::Phone::Management::Deployment::InstallationManager^ wintRtInstance);
  ::Windows::Phone::Management::Deployment::InstallationManager^ UnwrapInstallationManager(Local<Value> value);
  
  v8::Local<v8::Value> WrapPackageInstallResult(::Windows::Phone::Management::Deployment::PackageInstallResult^ wintRtInstance);
  ::Windows::Phone::Management::Deployment::PackageInstallResult^ UnwrapPackageInstallResult(Local<Value> value);
  



  static void InitEnterpriseEnrollmentStatusEnum(const Local<Object> exports) {
    HandleScope scope;

    Local<Object> enumObject = Nan::New<Object>();

    Nan::Set(exports, Nan::New<String>("EnterpriseEnrollmentStatus").ToLocalChecked(), enumObject);
    Nan::Set(enumObject, Nan::New<String>("success").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::Phone::Management::Deployment::EnterpriseEnrollmentStatus::Success)));
    Nan::Set(enumObject, Nan::New<String>("cancelledByUser").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::Phone::Management::Deployment::EnterpriseEnrollmentStatus::CancelledByUser)));
    Nan::Set(enumObject, Nan::New<String>("unknownFailure").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::Phone::Management::Deployment::EnterpriseEnrollmentStatus::UnknownFailure)));
  }

  static void InitEnterpriseStatusEnum(const Local<Object> exports) {
    HandleScope scope;

    Local<Object> enumObject = Nan::New<Object>();

    Nan::Set(exports, Nan::New<String>("EnterpriseStatus").ToLocalChecked(), enumObject);
    Nan::Set(enumObject, Nan::New<String>("enrolled").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::Phone::Management::Deployment::EnterpriseStatus::Enrolled)));
    Nan::Set(enumObject, Nan::New<String>("disabled").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::Phone::Management::Deployment::EnterpriseStatus::Disabled)));
    Nan::Set(enumObject, Nan::New<String>("revoked").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::Phone::Management::Deployment::EnterpriseStatus::Revoked)));
    Nan::Set(enumObject, Nan::New<String>("expired").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::Phone::Management::Deployment::EnterpriseStatus::Expired)));
  }



  class Enterprise : 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>("Enterprise").ToLocalChecked());
        localRef->InstanceTemplate()->SetInternalFieldCount(1);





          
            Nan::SetAccessor(localRef->PrototypeTemplate(), Nan::New<String>("enrollmentValidFrom").ToLocalChecked(), EnrollmentValidFromGetter);
            Nan::SetAccessor(localRef->PrototypeTemplate(), Nan::New<String>("enrollmentValidTo").ToLocalChecked(), EnrollmentValidToGetter);
            Nan::SetAccessor(localRef->PrototypeTemplate(), Nan::New<String>("id").ToLocalChecked(), IdGetter);
            Nan::SetAccessor(localRef->PrototypeTemplate(), Nan::New<String>("name").ToLocalChecked(), NameGetter);
            Nan::SetAccessor(localRef->PrototypeTemplate(), Nan::New<String>("status").ToLocalChecked(), StatusGetter);
            Nan::SetAccessor(localRef->PrototypeTemplate(), Nan::New<String>("workplaceId").ToLocalChecked(), WorkplaceIdGetter);

        Local<Object> constructor = Nan::To<Object>(Nan::GetFunction(localRef).ToLocalChecked()).ToLocalChecked();
        Nan::SetMethod(constructor, "castFrom", CastFrom);



        Nan::Set(exports, Nan::New<String>("Enterprise").ToLocalChecked(), constructor);
      }

      virtual ::Platform::Object^ GetObjectInstance() const override {
        return _instance;
      }

    private:

      Enterprise(::Windows::Phone::Management::Deployment::Enterprise^ 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::Phone::Management::Deployment::Enterprise^ winRtInstance;


      if (info.Length() == 1 && OpaqueWrapper::IsOpaqueWrapper(info[0]) &&
        NodeRT::Utils::IsWinRtWrapperOf<::Windows::Phone::Management::Deployment::Enterprise^>(info[0])) {
        try {
          winRtInstance = (::Windows::Phone::Management::Deployment::Enterprise^) 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());

      Enterprise *wrapperInstance = new Enterprise(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::Phone::Management::Deployment::Enterprise^>(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::Phone::Management::Deployment::Enterprise^ winRtInstance;
      try {
        winRtInstance = (::Windows::Phone::Management::Deployment::Enterprise^) NodeRT::Utils::GetObjectInstance(info[0]);
      } catch (Platform::Exception ^exception) {
        NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
        return;
      }

      info.GetReturnValue().Set(WrapEnterprise(winRtInstance));
    }





    static void EnrollmentValidFromGetter(Local<String> property, const Nan::PropertyCallbackInfo<v8::Value> &info) {
      HandleScope scope;

      if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::Phone::Management::Deployment::Enterprise^>(info.This())) {
        return;
      }

      Enterprise *wrapper = Enterprise::Unwrap<Enterprise>(info.This());

      try  {
        ::Windows::Foundation::DateTime result = wrapper->_instance->EnrollmentValidFrom;
        info.GetReturnValue().Set(NodeRT::Utils::DateTimeToJS(result));
        return;
      } catch (Platform::Exception ^exception) {
        NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
        return;
      }
    }
      
    static void EnrollmentValidToGetter(Local<String> property, const Nan::PropertyCallbackInfo<v8::Value> &info) {
      HandleScope scope;

      if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::Phone::Management::Deployment::Enterprise^>(info.This())) {
        return;
      }

      Enterprise *wrapper = Enterprise::Unwrap<Enterprise>(info.This());

      try  {
        ::Windows::Foundation::DateTime result = wrapper->_instance->EnrollmentValidTo;
        info.GetReturnValue().Set(NodeRT::Utils::DateTimeToJS(result));
        return;
      } catch (Platform::Exception ^exception) {
        NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
        return;
      }
    }
      
    static void IdGetter(Local<String> property, const Nan::PropertyCallbackInfo<v8::Value> &info) {
      HandleScope scope;

      if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::Phone::Management::Deployment::Enterprise^>(info.This())) {
        return;
      }

      Enterprise *wrapper = Enterprise::Unwrap<Enterprise>(info.This());

      try  {
        ::Platform::Guid result = wrapper->_instance->Id;
        info.GetReturnValue().Set(NodeRT::Utils::GuidToJs(result));
        return;
      } catch (Platform::Exception ^exception) {
        NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
        return;
      }
    }
      
    static void NameGetter(Local<String> property, const Nan::PropertyCallbackInfo<v8::Value> &info) {
      HandleScope scope;

      if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::Phone::Management::Deployment::Enterprise^>(info.This())) {
        return;
      }

      Enterprise *wrapper = Enterprise::Unwrap<Enterprise>(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 StatusGetter(Local<String> property, const Nan::PropertyCallbackInfo<v8::Value> &info) {
      HandleScope scope;

      if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::Phone::Management::Deployment::Enterprise^>(info.This())) {
        return;
      }

      Enterprise *wrapper = Enterprise::Unwrap<Enterprise>(info.This());

      try  {
        ::Windows::Phone::Management::Deployment::EnterpriseStatus result = wrapper->_instance->Status;
        info.GetReturnValue().Set(Nan::New<Integer>(static_cast<int>(result)));
        return;
      } catch (Platform::Exception ^exception) {
        NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
        return;
      }
    }
      
    static void WorkplaceIdGetter(Local<String> property, const Nan::PropertyCallbackInfo<v8::Value> &info) {
      HandleScope scope;

      if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::Phone::Management::Deployment::Enterprise^>(info.This())) {
        return;
      }

      Enterprise *wrapper = Enterprise::Unwrap<Enterprise>(info.This());

      try  {
        int result = wrapper->_instance->WorkplaceId;
        info.GetReturnValue().Set(Nan::New<Integer>(result));
        return;
      } catch (Platform::Exception ^exception) {
        NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
        return;
      }
    }
      


    private:
      ::Windows::Phone::Management::Deployment::Enterprise^ _instance;
      static Persistent<FunctionTemplate> s_constructorTemplate;

      friend v8::Local<v8::Value> WrapEnterprise(::Windows::Phone::Management::Deployment::Enterprise^ wintRtInstance);
      friend ::Windows::Phone::Management::Deployment::Enterprise^ UnwrapEnterprise(Local<Value> value);
  };

  Persistent<FunctionTemplate> Enterprise::s_constructorTemplate;

  v8::Local<v8::Value> WrapEnterprise(::Windows::Phone::Management::Deployment::Enterprise^ 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>(Enterprise::s_constructorTemplate);
    return scope.Escape(Nan::NewInstance(Nan::GetFunction(localRef).ToLocalChecked(),_countof(args), args).ToLocalChecked());
  }

  ::Windows::Phone::Management::Deployment::Enterprise^ UnwrapEnterprise(Local<Value> value) {
     return Enterprise::Unwrap<Enterprise>(Nan::To<Object>(value).ToLocalChecked())->_instance;
  }

  void InitEnterprise(Local<Object> exports) {
    Enterprise::Init(exports);
  }

  class EnterpriseEnrollmentManager : 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>("EnterpriseEnrollmentManager").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>(ValidateEnterprisesAsync)).ToLocalChecked();
        Nan::Set(constructor, Nan::New<String>("validateEnterprisesAsync").ToLocalChecked(), func);
        func = Nan::GetFunction(Nan::New<FunctionTemplate>(RequestEnrollmentAsync)).ToLocalChecked();
        Nan::Set(constructor, Nan::New<String>("requestEnrollmentAsync").ToLocalChecked(), func);
        func = Nan::GetFunction(Nan::New<FunctionTemplate>(RequestUnenrollmentAsync)).ToLocalChecked();
        Nan::Set(constructor, Nan::New<String>("requestUnenrollmentAsync").ToLocalChecked(), func);
        Nan::SetAccessor(constructor, Nan::New<String>("currentEnterprise").ToLocalChecked(), CurrentEnterpriseGetter);
        Nan::SetAccessor(constructor, Nan::New<String>("enrolledEnterprises").ToLocalChecked(), EnrolledEnterprisesGetter);


        Nan::Set(exports, Nan::New<String>("EnterpriseEnrollmentManager").ToLocalChecked(), constructor);
      }

      virtual ::Platform::Object^ GetObjectInstance() const override {
        return _instance;
      }

    private:

      EnterpriseEnrollmentManager(::Windows::Phone::Management::Deployment::EnterpriseEnrollmentManager^ 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::Phone::Management::Deployment::EnterpriseEnrollmentManager^ winRtInstance;


      if (info.Length() == 1 && OpaqueWrapper::IsOpaqueWrapper(info[0]) &&
        NodeRT::Utils::IsWinRtWrapperOf<::Windows::Phone::Management::Deployment::EnterpriseEnrollmentManager^>(info[0])) {
        try {
          winRtInstance = (::Windows::Phone::Management::Deployment::EnterpriseEnrollmentManager^) 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());

      EnterpriseEnrollmentManager *wrapperInstance = new EnterpriseEnrollmentManager(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::Phone::Management::Deployment::EnterpriseEnrollmentManager^>(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::Phone::Management::Deployment::EnterpriseEnrollmentManager^ winRtInstance;
      try {
        winRtInstance = (::Windows::Phone::Management::Deployment::EnterpriseEnrollmentManager^) NodeRT::Utils::GetObjectInstance(info[0]);
      } catch (Platform::Exception ^exception) {
        NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
        return;
      }

      info.GetReturnValue().Set(WrapEnterpriseEnrollmentManager(winRtInstance));
    }




    static void ValidateEnterprisesAsync(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::IAsyncAction^ op;


      if (info.Length() == 1)
      {
        try
        {
          op = ::Windows::Phone::Management::Deployment::EnterpriseEnrollmentManager::ValidateEnterprisesAsync();
        } 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<void> t)
      {
        try {
          t.get();
          NodeUtils::Async::RunCallbackOnMain(asyncToken, [](NodeUtils::InvokeCallbackDelegate invokeCallback) {


                Local<Value> args[] = {Undefined()};


            invokeCallback(_countof(args), args);
          });
        }
        catch (Platform::Exception^ exception)
        {
          NodeUtils::Async::RunCallbackOnMain(asyncToken, [exception](NodeUtils::InvokeCallbackDelegate invokeCallback) {

            Local<Value> error = NodeRT::Utils::WinRtExceptionToJsError(exception);

            Local<Value> args[] = {error};
            invokeCallback(_countof(args), args);
          });
        }
      });
    }

    static void RequestEnrollmentAsync(Nan::NAN_METHOD_ARGS_TYPE info) {
      HandleScope scope;

      if (info.Length() == 0 || !info[info.Length() -1]->IsFunction()) {
        Nan::ThrowError(Nan::Error(NodeRT::Utils::NewString(L"Bad arguments: No callback was given")));
        return;
      }

      ::Windows::Foundation::IAsyncOperation<::Windows::Phone::Management::Deployment::EnterpriseEnrollmentResult^>^ op;


      if (info.Length() == 2
          && info[0]->IsString())
      {
        try
        {
          Platform::String^ arg0 = ref new Platform::String(NodeRT::Utils::StringToWchar(v8::String::Value(v8::Isolate::GetCurrent(), info[0])));
            
          op = ::Windows::Phone::Management::Deployment::EnterpriseEnrollmentManager::RequestEnrollmentAsync(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::Phone::Management::Deployment::EnterpriseEnrollmentResult^> t)
      {
        try {
          auto result = t.get();
          NodeUtils::Async::RunCallbackOnMain(asyncToken, [result](NodeUtils::InvokeCallbackDelegate invokeCallback) {


            Local<Value> error;
            Local<Value> arg1;
            {
              TryCatch tryCatch;
              arg1 = WrapEnterpriseEnrollmentResult(result);
              if (tryCatch.HasCaught())
              {
                error = Nan::To<Object>(tryCatch.Exception()).ToLocalChecked();
              }
              else
              {
                error = Undefined();
              }
              if (arg1.IsEmpty()) arg1 = Undefined();
            }
            Local<Value> args[] = {error, arg1};


            invokeCallback(_countof(args), args);
          });
        }
        catch (Platform::Exception^ exception)
        {
          NodeUtils::Async::RunCallbackOnMain(asyncToken, [exception](NodeUtils::InvokeCallbackDelegate invokeCallback) {

            Local<Value> error = NodeRT::Utils::WinRtExceptionToJsError(exception);

            Local<Value> args[] = {error};
            invokeCallback(_countof(args), args);
          });
        }
      });
    }

    static void RequestUnenrollmentAsync(Nan::NAN_METHOD_ARGS_TYPE info) {
      HandleScope scope;

      if (info.Length() == 0 || !info[info.Length() -1]->IsFunction()) {
        Nan::ThrowError(Nan::Error(NodeRT::Utils::NewString(L"Bad arguments: No callback was given")));
        return;
      }

      ::Windows::Foundation::IAsyncOperation<bool>^ op;


      if (info.Length() == 2
          && NodeRT::Utils::IsWinRtWrapperOf<::Windows::Phone::Management::Deployment::Enterprise^>(info[0]))
      {
        try
        {
          ::Windows::Phone::Management::Deployment::Enterprise^ arg0 = UnwrapEnterprise(info[0]);
            
          op = ::Windows::Phone::Management::Deployment::EnterpriseEnrollmentManager::RequestUnenrollmentAsync(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<bool> t)
      {
        try {
          auto result = t.get();
          NodeUtils::Async::RunCallbackOnMain(asyncToken, [result](NodeUtils::InvokeCallbackDelegate invokeCallback) {


            Local<Value> error;
            Local<Value> arg1;
            {
              TryCatch tryCatch;
              arg1 = Nan::New<Boolean>(result);
              if (tryCatch.HasCaught())
              {
                error = Nan::To<Object>(tryCatch.Exception()).ToLocalChecked();
              }
              else
              {
                error = Undefined();
              }
              if (arg1.IsEmpty()) arg1 = Undefined();
            }
            Local<Value> args[] = {error, arg1};


            invokeCallback(_countof(args), args);
          });
        }
        catch (Platform::Exception^ exception)
        {
          NodeUtils::Async::RunCallbackOnMain(asyncToken, [exception](NodeUtils::InvokeCallbackDelegate invokeCallback) {

            Local<Value> error = NodeRT::Utils::WinRtExceptionToJsError(exception);

            Local<Value> args[] = {error};
            invokeCallback(_countof(args), args);
          });
        }
      });
    }




    static void CurrentEnterpriseGetter(Local<String> property, const Nan::PropertyCallbackInfo<v8::Value> &info) {
      HandleScope scope;

      try
      {
        ::Windows::Phone::Management::Deployment::Enterprise^ result = ::Windows::Phone::Management::Deployment::EnterpriseEnrollmentManager::CurrentEnterprise;
        info.GetReturnValue().Set(WrapEnterprise(result));
        return;
      } catch (Platform::Exception ^exception) {
        NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
        return;
      }
    }
      

    static void EnrolledEnterprisesGetter(Local<String> property, const Nan::PropertyCallbackInfo<v8::Value> &info) {
      HandleScope scope;

      try
      {
        ::Windows::Foundation::Collections::IVectorView<::Windows::Phone::Management::Deployment::Enterprise^>^ result = ::Windows::Phone::Management::Deployment::EnterpriseEnrollmentManager::EnrolledEnterprises;
        info.GetReturnValue().Set(NodeRT::Collections::VectorViewWrapper<::Windows::Phone::Management::Deployment::Enterprise^>::CreateVectorViewWrapper(result, 
            [](::Windows::Phone::Management::Deployment::Enterprise^ val) -> Local<Value> {
              return WrapEnterprise(val);
            },
            [](Local<Value> value) -> bool {
              return NodeRT::Utils::IsWinRtWrapperOf<::Windows::Phone::Management::Deployment::Enterprise^>(value);
            },
            [](Local<Value> value) -> ::Windows::Phone::Management::Deployment::Enterprise^ {
              return UnwrapEnterprise(value);
            }
          ));
        return;
      } catch (Platform::Exception ^exception) {
        NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
        return;
      }
    }
      

    private:
      ::Windows::Phone::Management::Deployment::EnterpriseEnrollmentManager^ _instance;
      static Persistent<FunctionTemplate> s_constructorTemplate;

      friend v8::Local<v8::Value> WrapEnterpriseEnrollmentManager(::Windows::Phone::Management::Deployment::EnterpriseEnrollmentManager^ wintRtInstance);
      friend ::Windows::Phone::Management::Deployment::EnterpriseEnrollmentManager^ UnwrapEnterpriseEnrollmentManager(Local<Value> value);
  };

  Persistent<FunctionTemplate> EnterpriseEnrollmentManager::s_constructorTemplate;

  v8::Local<v8::Value> WrapEnterpriseEnrollmentManager(::Windows::Phone::Management::Deployment::EnterpriseEnrollmentManager^ 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>(EnterpriseEnrollmentManager::s_constructorTemplate);
    return scope.Escape(Nan::NewInstance(Nan::GetFunction(localRef).ToLocalChecked(),_countof(args), args).ToLocalChecked());
  }

  ::Windows::Phone::Management::Deployment::EnterpriseEnrollmentManager^ UnwrapEnterpriseEnrollmentManager(Local<Value> value) {
     return EnterpriseEnrollmentManager::Unwrap<EnterpriseEnrollmentManager>(Nan::To<Object>(value).ToLocalChecked())->_instance;
  }

  void InitEnterpriseEnrollmentManager(Local<Object> exports) {
    EnterpriseEnrollmentManager::Init(exports);
  }

  class EnterpriseEnrollmentResult : 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>("EnterpriseEnrollmentResult").ToLocalChecked());
        localRef->InstanceTemplate()->SetInternalFieldCount(1);





          
            Nan::SetAccessor(localRef->PrototypeTemplate(), Nan::New<String>("enrolledEnterprise").ToLocalChecked(), EnrolledEnterpriseGetter);
            Nan::SetAccessor(localRef->PrototypeTemplate(), Nan::New<String>("status").ToLocalChecked(), StatusGetter);

        Local<Object> constructor = Nan::To<Object>(Nan::GetFunction(localRef).ToLocalChecked()).ToLocalChecked();
        Nan::SetMethod(constructor, "castFrom", CastFrom);



        Nan::Set(exports, Nan::New<String>("EnterpriseEnrollmentResult").ToLocalChecked(), constructor);
      }

      virtual ::Platform::Object^ GetObjectInstance() const override {
        return _instance;
      }

    private:

      EnterpriseEnrollmentResult(::Windows::Phone::Management::Deployment::EnterpriseEnrollmentResult^ 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::Phone::Management::Deployment::EnterpriseEnrollmentResult^ winRtInstance;


      if (info.Length() == 1 && OpaqueWrapper::IsOpaqueWrapper(info[0]) &&
        NodeRT::Utils::IsWinRtWrapperOf<::Windows::Phone::Management::Deployment::EnterpriseEnrollmentResult^>(info[0])) {
        try {
          winRtInstance = (::Windows::Phone::Management::Deployment::EnterpriseEnrollmentResult^) 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());

      EnterpriseEnrollmentResult *wrapperInstance = new EnterpriseEnrollmentResult(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::Phone::Management::Deployment::EnterpriseEnrollmentResult^>(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::Phone::Management::Deployment::EnterpriseEnrollmentResult^ winRtInstance;
      try {
        winRtInstance = (::Windows::Phone::Management::Deployment::EnterpriseEnrollmentResult^) NodeRT::Utils::GetObjectInstance(info[0]);
      } catch (Platform::Exception ^exception) {
        NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
        return;
      }

      info.GetReturnValue().Set(WrapEnterpriseEnrollmentResult(winRtInstance));
    }





    static void EnrolledEnterpriseGetter(Local<String> property, const Nan::PropertyCallbackInfo<v8::Value> &info) {
      HandleScope scope;

      if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::Phone::Management::Deployment::EnterpriseEnrollmentResult^>(info.This())) {
        return;
      }

      EnterpriseEnrollmentResult *wrapper = EnterpriseEnrollmentResult::Unwrap<EnterpriseEnrollmentResult>(info.This());

      try  {
        ::Windows::Phone::Management::Deployment::Enterprise^ result = wrapper->_instance->EnrolledEnterprise;
        info.GetReturnValue().Set(WrapEnterprise(result));
        return;
      } catch (Platform::Exception ^exception) {
        NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
        return;
      }
    }
      
    static void StatusGetter(Local<String> property, const Nan::PropertyCallbackInfo<v8::Value> &info) {
      HandleScope scope;

      if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::Phone::Management::Deployment::EnterpriseEnrollmentResult^>(info.This())) {
        return;
      }

      EnterpriseEnrollmentResult *wrapper = EnterpriseEnrollmentResult::Unwrap<EnterpriseEnrollmentResult>(info.This());

      try  {
        ::Windows::Phone::Management::Deployment::EnterpriseEnrollmentStatus result = wrapper->_instance->Status;
        info.GetReturnValue().Set(Nan::New<Integer>(static_cast<int>(result)));
        return;
      } catch (Platform::Exception ^exception) {
        NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
        return;
      }
    }
      


    private:
      ::Windows::Phone::Management::Deployment::EnterpriseEnrollmentResult^ _instance;
      static Persistent<FunctionTemplate> s_constructorTemplate;

      friend v8::Local<v8::Value> WrapEnterpriseEnrollmentResult(::Windows::Phone::Management::Deployment::EnterpriseEnrollmentResult^ wintRtInstance);
      friend ::Windows::Phone::Management::Deployment::EnterpriseEnrollmentResult^ UnwrapEnterpriseEnrollmentResult(Local<Value> value);
  };

  Persistent<FunctionTemplate> EnterpriseEnrollmentResult::s_constructorTemplate;

  v8::Local<v8::Value> WrapEnterpriseEnrollmentResult(::Windows::Phone::Management::Deployment::EnterpriseEnrollmentResult^ 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>(EnterpriseEnrollmentResult::s_constructorTemplate);
    return scope.Escape(Nan::NewInstance(Nan::GetFunction(localRef).ToLocalChecked(),_countof(args), args).ToLocalChecked());
  }

  ::Windows::Phone::Management::Deployment::EnterpriseEnrollmentResult^ UnwrapEnterpriseEnrollmentResult(Local<Value> value) {
     return EnterpriseEnrollmentResult::Unwrap<EnterpriseEnrollmentResult>(Nan::To<Object>(value).ToLocalChecked())->_instance;
  }

  void InitEnterpriseEnrollmentResult(Local<Object> exports) {
    EnterpriseEnrollmentResult::Init(exports);
  }

  class InstallationManager : 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>("InstallationManager").ToLocalChecked());
        localRef->InstanceTemplate()->SetInternalFieldCount(1);

        Local<Function> func;
        Local<FunctionTemplate> funcTemplate;





        Local<Object> constructor = Nan::To<Object>(Nan::GetFunction(localRef).ToLocalChecked()).ToLocalChecked();
        Nan::SetMethod(constructor, "castFrom", CastFrom);

        Nan::SetMethod(constructor, "findPackages", FindPackages);
        Nan::SetMethod(constructor, "getPendingPackageInstalls", GetPendingPackageInstalls);
        Nan::SetMethod(constructor, "findPackagesForCurrentPublisher", FindPackagesForCurrentPublisher);
        func = Nan::GetFunction(Nan::New<FunctionTemplate>(RemovePackageAsync)).ToLocalChecked();
        Nan::Set(constructor, Nan::New<String>("removePackageAsync").ToLocalChecked(), func);
        func = Nan::GetFunction(Nan::New<FunctionTemplate>(RegisterPackageAsync)).ToLocalChecked();
        Nan::Set(constructor, Nan::New<String>("registerPackageAsync").ToLocalChecked(), func);
        func = Nan::GetFunction(Nan::New<FunctionTemplate>(AddPackageAsync)).ToLocalChecked();
        Nan::Set(constructor, Nan::New<String>("addPackageAsync").ToLocalChecked(), func);


        Nan::Set(exports, Nan::New<String>("InstallationManager").ToLocalChecked(), constructor);
      }

      virtual ::Platform::Object^ GetObjectInstance() const override {
        return _instance;
      }

    private:

      InstallationManager(::Windows::Phone::Management::Deployment::InstallationManager^ 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::Phone::Management::Deployment::InstallationManager^ winRtInstance;


      if (info.Length() == 1 && OpaqueWrapper::IsOpaqueWrapper(info[0]) &&
        NodeRT::Utils::IsWinRtWrapperOf<::Windows::Phone::Management::Deployment::InstallationManager^>(info[0])) {
        try {
          winRtInstance = (::Windows::Phone::Management::Deployment::InstallationManager^) 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());

      InstallationManager *wrapperInstance = new InstallationManager(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::Phone::Management::Deployment::InstallationManager^>(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::Phone::Management::Deployment::InstallationManager^ winRtInstance;
      try {
        winRtInstance = (::Windows::Phone::Management::Deployment::InstallationManager^) NodeRT::Utils::GetObjectInstance(info[0]);
      } catch (Platform::Exception ^exception) {
        NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
        return;
      }

      info.GetReturnValue().Set(WrapInstallationManager(winRtInstance));
    }




    static void RemovePackageAsync(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::Phone::Management::Deployment::PackageInstallResult^, unsigned int>^ op;


      if (info.Length() == 3
          && info[0]->IsString()
          && info[1]->IsInt32())
      {
        try
        {
          Platform::String^ arg0 = ref new Platform::String(NodeRT::Utils::StringToWchar(v8::String::Value(v8::Isolate::GetCurrent(), info[0])));
          ::Windows::Management::Deployment::RemovalOptions arg1 = static_cast<::Windows::Management::Deployment::RemovalOptions>(Nan::To<int32_t>(info[1]).FromMaybe(0));
            
          op = ::Windows::Phone::Management::Deployment::InstallationManager::RemovePackageAsync(arg0,arg1);
        } catch (Platform::Exception ^exception) {
            NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
            return;
        }
      }
 else {
        Nan::ThrowError(Nan::Error(NodeRT::Utils::NewString(L"Bad arguments: no suitable overload found")));
        return;
      }

      auto opTask = create_task(op);
      uv_async_t* asyncToken = NodeUtils::Async::GetAsyncToken(info[info.Length() -1].As<Function>());

      opTask.then( [asyncToken] (task<::Windows::Phone::Management::Deployment::PackageInstallResult^> t)
      {
        try {
          auto result = t.get();
          NodeUtils::Async::RunCallbackOnMain(asyncToken, [result](NodeUtils::InvokeCallbackDelegate invokeCallback) {


            Local<Value> error;
            Local<Value> arg1;
            {
              TryCatch tryCatch;
              arg1 = WrapPackageInstallResult(result);
              if (tryCatch.HasCaught())
              {
                error = Nan::To<Object>(tryCatch.Exception()).ToLocalChecked();
              }
              else
              {
                error = Undefined();
              }
              if (arg1.IsEmpty()) arg1 = Undefined();
            }
            Local<Value> args[] = {error, arg1};


            invokeCallback(_countof(args), args);
          });
        }
        catch (Platform::Exception^ exception)
        {
          NodeUtils::Async::RunCallbackOnMain(asyncToken, [exception](NodeUtils::InvokeCallbackDelegate invokeCallback) {

            Local<Value> error = NodeRT::Utils::WinRtExceptionToJsError(exception);

            Local<Value> args[] = {error};
            invokeCallback(_countof(args), args);
          });
        }
      });
    }

    static void RegisterPackageAsync(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::Phone::Management::Deployment::PackageInstallResult^, unsigned int>^ op;


      if (info.Length() == 4
          && NodeRT::Utils::IsWinRtWrapperOf<::Windows::Foundation::Uri^>(info[0])
          && (NodeRT::Utils::IsWinRtWrapperOf<::Windows::Foundation::Collections::IIterable<::Windows::Foundation::Uri^>^>(info[1]) || info[1]->IsArray())
          && info[2]->IsInt32())
      {
        try
        {
          ::Windows::Foundation::Uri^ arg0 = dynamic_cast<::Windows::Foundation::Uri^>(NodeRT::Utils::GetObjectInstance(info[0]));
          ::Windows::Foundation::Collections::IIterable<::Windows::Foundation::Uri^>^ arg1 = 
            [] (v8::Local<v8::Value> value) -> ::Windows::Foundation::Collections::IIterable<::Windows::Foundation::Uri^>^
            {
              if (value->IsArray())
              {
                return NodeRT::Collections::JsArrayToWinrtVector<::Windows::Foundation::Uri^>(value.As<Array>(), 
                 [](Local<Value> value) -> bool {
                   return NodeRT::Utils::IsWinRtWrapperOf<::Windows::Foundation::Uri^>(value);
                 },
                 [](Local<Value> value) -> ::Windows::Foundation::Uri^ {
                   return dynamic_cast<::Windows::Foundation::Uri^>(NodeRT::Utils::GetObjectInstance(value));
                 }
                );
              }
              else
              {
                return dynamic_cast<::Windows::Foundation::Collections::IIterable<::Windows::Foundation::Uri^>^>(NodeRT::Utils::GetObjectInstance(value));
              }
            } (info[1]);
          ::Windows::Management::Deployment::DeploymentOptions arg2 = static_cast<::Windows::Management::Deployment::DeploymentOptions>(Nan::To<int32_t>(info[2]).FromMaybe(0));
            
          op = ::Windows::Phone::Management::Deployment::InstallationManager::RegisterPackageAsync(arg0,arg1,arg2);
        } 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::Phone::Management::Deployment::PackageInstallResult^> t)
      {
        try {
          auto result = t.get();
          NodeUtils::Async::RunCallbackOnMain(asyncToken, [result](NodeUtils::InvokeCallbackDelegate invokeCallback) {


            Local<Value> error;
            Local<Value> arg1;
            {
              TryCatch tryCatch;
              arg1 = WrapPackageInstallResult(result);
              if (tryCatch.HasCaught())
              {
                error = Nan::To<Object>(tryCatch.Exception()).ToLocalChecked();
              }
              else
              {
                error = Undefined();
              }
              if (arg1.IsEmpty()) arg1 = Undefined();
            }
            Local<Value> args[] = {error, arg1};


            invokeCallback(_countof(args), args);
          });
        }
        catch (Platform::Exception^ exception)
        {
          NodeUtils::Async::RunCallbackOnMain(asyncToken, [exception](NodeUtils::InvokeCallbackDelegate invokeCallback) {

            Local<Value> error = NodeRT::Utils::WinRtExceptionToJsError(exception);

            Local<Value> args[] = {error};
            invokeCallback(_countof(args), args);
          });
        }
      });
    }

    static void AddPackageAsync(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::Phone::Management::Deployment::PackageInstallResult^, unsigned int>^ op;


      if (info.Length() == 3
          && info[0]->IsString()
          && NodeRT::Utils::IsWinRtWrapperOf<::Windows::Foundation::Uri^>(info[1]))
      {
        try
        {
          Platform::String^ arg0 = ref new Platform::String(NodeRT::Utils::StringToWchar(v8::String::Value(v8::Isolate::GetCurrent(), info[0])));
          ::Windows::Foundation::Uri^ arg1 = dynamic_cast<::Windows::Foundation::Uri^>(NodeRT::Utils::GetObjectInstance(info[1]));
            
          op = ::Windows::Phone::Management::Deployment::InstallationManager::AddPackageAsync(arg0,arg1);
        } catch (Platform::Exception ^exception) {
            NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
            return;
        }
      }
      else if (info.Length() == 6
          && info[0]->IsString()
          && NodeRT::Utils::IsWinRtWrapperOf<::Windows::Foundation::Uri^>(info[1])
          && info[2]->IsString()
          && info[3]->IsString()
          && NodeRT::Utils::IsWinRtWrapperOf<::Windows::Foundation::Uri^>(info[4]))
      {
        try
        {
          Platform::String^ arg0 = ref new Platform::String(NodeRT::Utils::StringToWchar(v8::String::Value(v8::Isolate::GetCurrent(), info[0])));
          ::Windows::Foundation::Uri^ arg1 = dynamic_cast<::Windows::Foundation::Uri^>(NodeRT::Utils::GetObjectInstance(info[1]));
          Platform::String^ arg2 = ref new Platform::String(NodeRT::Utils::StringToWchar(v8::String::Value(v8::Isolate::GetCurrent(), info[2])));
          Platform::String^ arg3 = ref new Platform::String(NodeRT::Utils::StringToWchar(v8::String::Value(v8::Isolate::GetCurrent(), info[3])));
          ::Windows::Foundation::Uri^ arg4 = dynamic_cast<::Windows::Foundation::Uri^>(NodeRT::Utils::GetObjectInstance(info[4]));
            
          op = ::Windows::Phone::Management::Deployment::InstallationManager::AddPackageAsync(arg0,arg1,arg2,arg3,arg4);
        } 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::Phone::Management::Deployment::PackageInstallResult^> t)
      {
        try {
          auto result = t.get();
          NodeUtils::Async::RunCallbackOnMain(asyncToken, [result](NodeUtils::InvokeCallbackDelegate invokeCallback) {


            Local<Value> error;
            Local<Value> arg1;
            {
              TryCatch tryCatch;
              arg1 = WrapPackageInstallResult(result);
              if (tryCatch.HasCaught())
              {
                error = Nan::To<Object>(tryCatch.Exception()).ToLocalChecked();
              }
              else
              {
                error = Undefined();
              }
              if (arg1.IsEmpty()) arg1 = Undefined();
            }
            Local<Value> args[] = {error, arg1};


            invokeCallback(_countof(args), args);
          });
        }
        catch (Platform::Exception^ exception)
        {
          NodeUtils::Async::RunCallbackOnMain(asyncToken, [exception](NodeUtils::InvokeCallbackDelegate invokeCallback) {

            Local<Value> error = NodeRT::Utils::WinRtExceptionToJsError(exception);

            Local<Value> args[] = {error};
            invokeCallback(_countof(args), args);
          });
        }
      });
    }


    static void FindPackages(Nan::NAN_METHOD_ARGS_TYPE info) {
      HandleScope scope;

      if (info.Length() == 2
        && info[0]->IsString()
        && info[1]->IsString())
      {
        try
        {
          Platform::String^ arg0 = ref new Platform::String(NodeRT::Utils::StringToWchar(v8::String::Value(v8::Isolate::GetCurrent(), info[0])));
          Platform::String^ arg1 = ref new Platform::String(NodeRT::Utils::StringToWchar(v8::String::Value(v8::Isolate::GetCurrent(), info[1])));
          
          ::Windows::Foundation::Collections::IIterable<::Windows::ApplicationModel::Package^>^ result;
          result = ::Windows::Phone::Management::Deployment::InstallationManager::FindPackages(arg0, arg1);
          info.GetReturnValue().Set(NodeRT::Collections::IterableWrapper<::Windows::ApplicationModel::Package^>::CreateIterableWrapper(result, 
            [](::Windows::ApplicationModel::Package^ val) -> Local<Value> {
              return NodeRT::Utils::CreateExternalWinRTObject("Windows.ApplicationModel", "Package", val);
            }
          ));
          return;
        }
        catch (Platform::Exception ^exception)
        {
          NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
          return;
        }
      }
      else if (info.Length() == 0)
      {
        try
        {
          ::Windows::Foundation::Collections::IIterable<::Windows::ApplicationModel::Package^>^ result;
          result = ::Windows::Phone::Management::Deployment::InstallationManager::FindPackages();
          info.GetReturnValue().Set(NodeRT::Collections::IterableWrapper<::Windows::ApplicationModel::Package^>::CreateIterableWrapper(result, 
            [](::Windows::ApplicationModel::Package^ val) -> Local<Value> {
              return NodeRT::Utils::CreateExternalWinRTObject("Windows.ApplicationModel", "Package", val);
            }
          ));
          return;
        }
        catch (Platform::Exception ^exception)
        {
          NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
          return;
        }
      }
 else  {
        Nan::ThrowError(Nan::Error(NodeRT::Utils::NewString(L"Bad arguments: no suitable overload found")));
        return;
      }
    }

    static void GetPendingPackageInstalls(Nan::NAN_METHOD_ARGS_TYPE info) {
      HandleScope scope;

      if (info.Length() == 0)
      {
        try
        {
          ::Windows::Foundation::Collections::IIterable<::Windows::Foundation::IAsyncOperationWithProgress<::Windows::Phone::Management::Deployment::PackageInstallResult^, unsigned int>^>^ result;
          result = ::Windows::Phone::Management::Deployment::InstallationManager::GetPendingPackageInstalls();
          info.GetReturnValue().Set(NodeRT::Collections::IterableWrapper<::Windows::Foundation::IAsyncOperationWithProgress<::Windows::Phone::Management::Deployment::PackageInstallResult^, unsigned int>^>::CreateIterableWrapper(result, 
            [](::Windows::Foundation::IAsyncOperationWithProgress<::Windows::Phone::Management::Deployment::PackageInstallResult^, unsigned int>^ val) -> Local<Value> {
              return NodeRT::Utils::CreateExternalWinRTObject("Windows.Foundation", "IAsyncOperationWithProgress`2", val);
            }
          ));
          return;
        }
        catch (Platform::Exception ^exception)
        {
          NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
          return;
        }
      }
 else  {
        Nan::ThrowError(Nan::Error(NodeRT::Utils::NewString(L"Bad arguments: no suitable overload found")));
        return;
      }
    }

    static void FindPackagesForCurrentPublisher(Nan::NAN_METHOD_ARGS_TYPE info) {
      HandleScope scope;

      if (info.Length() == 0)
      {
        try
        {
          ::Windows::Foundation::Collections::IIterable<::Windows::ApplicationModel::Package^>^ result;
          result = ::Windows::Phone::Management::Deployment::InstallationManager::FindPackagesForCurrentPublisher();
          info.GetReturnValue().Set(NodeRT::Collections::IterableWrapper<::Windows::ApplicationModel::Package^>::CreateIterableWrapper(result, 
            [](::Windows::ApplicationModel::Package^ val) -> Local<Value> {
              return NodeRT::Utils::CreateExternalWinRTObject("Windows.ApplicationModel", "Package", val);
            }
          ));
          return;
        }
        catch (Platform::Exception ^exception)
        {
          NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
          return;
        }
      }
 else  {
        Nan::ThrowError(Nan::Error(NodeRT::Utils::NewString(L"Bad arguments: no suitable overload found")));
        return;
      }
    }



    private:
      ::Windows::Phone::Management::Deployment::InstallationManager^ _instance;
      static Persistent<FunctionTemplate> s_constructorTemplate;

      friend v8::Local<v8::Value> WrapInstallationManager(::Windows::Phone::Management::Deployment::InstallationManager^ wintRtInstance);
      friend ::Windows::Phone::Management::Deployment::InstallationManager^ UnwrapInstallationManager(Local<Value> value);
  };

  Persistent<FunctionTemplate> InstallationManager::s_constructorTemplate;

  v8::Local<v8::Value> WrapInstallationManager(::Windows::Phone::Management::Deployment::InstallationManager^ 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>(InstallationManager::s_constructorTemplate);
    return scope.Escape(Nan::NewInstance(Nan::GetFunction(localRef).ToLocalChecked(),_countof(args), args).ToLocalChecked());
  }

  ::Windows::Phone::Management::Deployment::InstallationManager^ UnwrapInstallationManager(Local<Value> value) {
     return InstallationManager::Unwrap<InstallationManager>(Nan::To<Object>(value).ToLocalChecked())->_instance;
  }

  void InitInstallationManager(Local<Object> exports) {
    InstallationManager::Init(exports);
  }

  class PackageInstallResult : 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>("PackageInstallResult").ToLocalChecked());
        localRef->InstanceTemplate()->SetInternalFieldCount(1);





          
            Nan::SetAccessor(localRef->PrototypeTemplate(), Nan::New<String>("installState").ToLocalChecked(), InstallStateGetter);
            Nan::SetAccessor(localRef->PrototypeTemplate(), Nan::New<String>("productId").ToLocalChecked(), ProductIdGetter);
            Nan::SetAccessor(localRef->PrototypeTemplate(), Nan::New<String>("errorText").ToLocalChecked(), ErrorTextGetter);

        Local<Object> constructor = Nan::To<Object>(Nan::GetFunction(localRef).ToLocalChecked()).ToLocalChecked();
        Nan::SetMethod(constructor, "castFrom", CastFrom);



        Nan::Set(exports, Nan::New<String>("PackageInstallResult").ToLocalChecked(), constructor);
      }

      virtual ::Platform::Object^ GetObjectInstance() const override {
        return _instance;
      }

    private:

      PackageInstallResult(::Windows::Phone::Management::Deployment::PackageInstallResult^ 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::Phone::Management::Deployment::PackageInstallResult^ winRtInstance;


      if (info.Length() == 1 && OpaqueWrapper::IsOpaqueWrapper(info[0]) &&
        NodeRT::Utils::IsWinRtWrapperOf<::Windows::Phone::Management::Deployment::PackageInstallResult^>(info[0])) {
        try {
          winRtInstance = (::Windows::Phone::Management::Deployment::PackageInstallResult^) 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());

      PackageInstallResult *wrapperInstance = new PackageInstallResult(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::Phone::Management::Deployment::PackageInstallResult^>(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::Phone::Management::Deployment::PackageInstallResult^ winRtInstance;
      try {
        winRtInstance = (::Windows::Phone::Management::Deployment::PackageInstallResult^) NodeRT::Utils::GetObjectInstance(info[0]);
      } catch (Platform::Exception ^exception) {
        NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
        return;
      }

      info.GetReturnValue().Set(WrapPackageInstallResult(winRtInstance));
    }





    static void InstallStateGetter(Local<String> property, const Nan::PropertyCallbackInfo<v8::Value> &info) {
      HandleScope scope;

      if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::Phone::Management::Deployment::PackageInstallResult^>(info.This())) {
        return;
      }

      PackageInstallResult *wrapper = PackageInstallResult::Unwrap<PackageInstallResult>(info.This());

      try  {
        ::Windows::Management::Deployment::PackageInstallState result = wrapper->_instance->InstallState;
        info.GetReturnValue().Set(Nan::New<Integer>(static_cast<int>(result)));
        return;
      } catch (Platform::Exception ^exception) {
        NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
        return;
      }
    }
      
    static void ProductIdGetter(Local<String> property, const Nan::PropertyCallbackInfo<v8::Value> &info) {
      HandleScope scope;

      if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::Phone::Management::Deployment::PackageInstallResult^>(info.This())) {
        return;
      }

      PackageInstallResult *wrapper = PackageInstallResult::Unwrap<PackageInstallResult>(info.This());

      try  {
        Platform::String^ result = wrapper->_instance->ProductId;
        info.GetReturnValue().Set(NodeRT::Utils::NewString(result->Data()));
        return;
      } catch (Platform::Exception ^exception) {
        NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
        return;
      }
    }
      
    static void ErrorTextGetter(Local<String> property, const Nan::PropertyCallbackInfo<v8::Value> &info) {
      HandleScope scope;

      if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::Phone::Management::Deployment::PackageInstallResult^>(info.This())) {
        return;
      }

      PackageInstallResult *wrapper = PackageInstallResult::Unwrap<PackageInstallResult>(info.This());

      try  {
        Platform::String^ result = wrapper->_instance->ErrorText;
        info.GetReturnValue().Set(NodeRT::Utils::NewString(result->Data()));
        return;
      } catch (Platform::Exception ^exception) {
        NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
        return;
      }
    }
      


    private:
      ::Windows::Phone::Management::Deployment::PackageInstallResult^ _instance;
      static Persistent<FunctionTemplate> s_constructorTemplate;

      friend v8::Local<v8::Value> WrapPackageInstallResult(::Windows::Phone::Management::Deployment::PackageInstallResult^ wintRtInstance);
      friend ::Windows::Phone::Management::Deployment::PackageInstallResult^ UnwrapPackageInstallResult(Local<Value> value);
  };

  Persistent<FunctionTemplate> PackageInstallResult::s_constructorTemplate;

  v8::Local<v8::Value> WrapPackageInstallResult(::Windows::Phone::Management::Deployment::PackageInstallResult^ 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>(PackageInstallResult::s_constructorTemplate);
    return scope.Escape(Nan::NewInstance(Nan::GetFunction(localRef).ToLocalChecked(),_countof(args), args).ToLocalChecked());
  }

  ::Windows::Phone::Management::Deployment::PackageInstallResult^ UnwrapPackageInstallResult(Local<Value> value) {
     return PackageInstallResult::Unwrap<PackageInstallResult>(Nan::To<Object>(value).ToLocalChecked())->_instance;
  }

  void InitPackageInstallResult(Local<Object> exports) {
    PackageInstallResult::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::Phone::Management::Deployment::InitEnterpriseEnrollmentStatusEnum(target);
      NodeRT::Windows::Phone::Management::Deployment::InitEnterpriseStatusEnum(target);
      NodeRT::Windows::Phone::Management::Deployment::InitEnterprise(target);
      NodeRT::Windows::Phone::Management::Deployment::InitEnterpriseEnrollmentManager(target);
      NodeRT::Windows::Phone::Management::Deployment::InitEnterpriseEnrollmentResult(target);
      NodeRT::Windows::Phone::Management::Deployment::InitInstallationManager(target);
      NodeRT::Windows::Phone::Management::Deployment::InitPackageInstallResult(target);


  NodeRT::Utils::RegisterNameSpace("Windows.Phone.Management.Deployment", target);
}



NODE_MODULE(binding, init)
