// 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 Data { namespace Pdf { 
  v8::Local<v8::Value> WrapPdfPageRenderOptions(::Windows::Data::Pdf::PdfPageRenderOptions^ wintRtInstance);
  ::Windows::Data::Pdf::PdfPageRenderOptions^ UnwrapPdfPageRenderOptions(Local<Value> value);
  
  v8::Local<v8::Value> WrapPdfPageDimensions(::Windows::Data::Pdf::PdfPageDimensions^ wintRtInstance);
  ::Windows::Data::Pdf::PdfPageDimensions^ UnwrapPdfPageDimensions(Local<Value> value);
  
  v8::Local<v8::Value> WrapPdfPage(::Windows::Data::Pdf::PdfPage^ wintRtInstance);
  ::Windows::Data::Pdf::PdfPage^ UnwrapPdfPage(Local<Value> value);
  
  v8::Local<v8::Value> WrapPdfDocument(::Windows::Data::Pdf::PdfDocument^ wintRtInstance);
  ::Windows::Data::Pdf::PdfDocument^ UnwrapPdfDocument(Local<Value> value);
  



  static void InitPdfPageRotationEnum(const Local<Object> exports) {
    HandleScope scope;

    Local<Object> enumObject = Nan::New<Object>();

    Nan::Set(exports, Nan::New<String>("PdfPageRotation").ToLocalChecked(), enumObject);
    Nan::Set(enumObject, Nan::New<String>("normal").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::Data::Pdf::PdfPageRotation::Normal)));
    Nan::Set(enumObject, Nan::New<String>("rotate90").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::Data::Pdf::PdfPageRotation::Rotate90)));
    Nan::Set(enumObject, Nan::New<String>("rotate180").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::Data::Pdf::PdfPageRotation::Rotate180)));
    Nan::Set(enumObject, Nan::New<String>("rotate270").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::Data::Pdf::PdfPageRotation::Rotate270)));
  }


  static bool IsRectJsObject(Local<Value> value) {
    if (!value->IsObject()) {
      return false;
    }

    Local<String> symbol;
    Local<Object> obj = Nan::To<Object>(value).ToLocalChecked();

    return true;
  }

  ::Windows::Foundation::Rect RectFromJsObject(Local<Value> value) {
    HandleScope scope;
    ::Windows::Foundation::Rect 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> RectToJsObject(::Windows::Foundation::Rect value) {
    EscapableHandleScope scope;

    Local<Object> obj = Nan::New<Object>();


    return scope.Escape(obj);
  }
  static bool IsColorJsObject(Local<Value> value) {
    if (!value->IsObject()) {
      return false;
    }

    Local<String> symbol;
    Local<Object> obj = Nan::To<Object>(value).ToLocalChecked();

    return true;
  }

  ::Windows::UI::Color ColorFromJsObject(Local<Value> value) {
    HandleScope scope;
    ::Windows::UI::Color 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> ColorToJsObject(::Windows::UI::Color value) {
    EscapableHandleScope scope;

    Local<Object> obj = Nan::New<Object>();


    return scope.Escape(obj);
  }
  static bool IsSizeJsObject(Local<Value> value) {
    if (!value->IsObject()) {
      return false;
    }

    Local<String> symbol;
    Local<Object> obj = Nan::To<Object>(value).ToLocalChecked();

    return true;
  }

  ::Windows::Foundation::Size SizeFromJsObject(Local<Value> value) {
    HandleScope scope;
    ::Windows::Foundation::Size 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> SizeToJsObject(::Windows::Foundation::Size value) {
    EscapableHandleScope scope;

    Local<Object> obj = Nan::New<Object>();


    return scope.Escape(obj);
  }

  class PdfPageRenderOptions : 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>("PdfPageRenderOptions").ToLocalChecked());
        localRef->InstanceTemplate()->SetInternalFieldCount(1);





          
            Nan::SetAccessor(localRef->PrototypeTemplate(), Nan::New<String>("sourceRect").ToLocalChecked(), SourceRectGetter, SourceRectSetter);
            Nan::SetAccessor(localRef->PrototypeTemplate(), Nan::New<String>("isIgnoringHighContrast").ToLocalChecked(), IsIgnoringHighContrastGetter, IsIgnoringHighContrastSetter);
            Nan::SetAccessor(localRef->PrototypeTemplate(), Nan::New<String>("destinationWidth").ToLocalChecked(), DestinationWidthGetter, DestinationWidthSetter);
            Nan::SetAccessor(localRef->PrototypeTemplate(), Nan::New<String>("destinationHeight").ToLocalChecked(), DestinationHeightGetter, DestinationHeightSetter);
            Nan::SetAccessor(localRef->PrototypeTemplate(), Nan::New<String>("bitmapEncoderId").ToLocalChecked(), BitmapEncoderIdGetter, BitmapEncoderIdSetter);
            Nan::SetAccessor(localRef->PrototypeTemplate(), Nan::New<String>("backgroundColor").ToLocalChecked(), BackgroundColorGetter, BackgroundColorSetter);

        Local<Object> constructor = Nan::To<Object>(Nan::GetFunction(localRef).ToLocalChecked()).ToLocalChecked();
        Nan::SetMethod(constructor, "castFrom", CastFrom);



        Nan::Set(exports, Nan::New<String>("PdfPageRenderOptions").ToLocalChecked(), constructor);
      }

      virtual ::Platform::Object^ GetObjectInstance() const override {
        return _instance;
      }

    private:

      PdfPageRenderOptions(::Windows::Data::Pdf::PdfPageRenderOptions^ 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::Data::Pdf::PdfPageRenderOptions^ winRtInstance;


      if (info.Length() == 1 && OpaqueWrapper::IsOpaqueWrapper(info[0]) &&
        NodeRT::Utils::IsWinRtWrapperOf<::Windows::Data::Pdf::PdfPageRenderOptions^>(info[0])) {
        try {
          winRtInstance = (::Windows::Data::Pdf::PdfPageRenderOptions^) NodeRT::Utils::GetObjectInstance(info[0]);
        } catch (Platform::Exception ^exception) {
          NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
          return;
        }
      }
      else if (info.Length() == 0)
      {
        try {
          winRtInstance = ref new ::Windows::Data::Pdf::PdfPageRenderOptions();
        } 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());

      PdfPageRenderOptions *wrapperInstance = new PdfPageRenderOptions(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::Data::Pdf::PdfPageRenderOptions^>(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::Data::Pdf::PdfPageRenderOptions^ winRtInstance;
      try {
        winRtInstance = (::Windows::Data::Pdf::PdfPageRenderOptions^) NodeRT::Utils::GetObjectInstance(info[0]);
      } catch (Platform::Exception ^exception) {
        NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
        return;
      }

      info.GetReturnValue().Set(WrapPdfPageRenderOptions(winRtInstance));
    }





    static void SourceRectGetter(Local<String> property, const Nan::PropertyCallbackInfo<v8::Value> &info) {
      HandleScope scope;

      if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::Data::Pdf::PdfPageRenderOptions^>(info.This())) {
        return;
      }

      PdfPageRenderOptions *wrapper = PdfPageRenderOptions::Unwrap<PdfPageRenderOptions>(info.This());

      try  {
        ::Windows::Foundation::Rect result = wrapper->_instance->SourceRect;
        info.GetReturnValue().Set(NodeRT::Utils::RectToJs(result));
        return;
      } catch (Platform::Exception ^exception) {
        NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
        return;
      }
    }
      
    static void SourceRectSetter(Local<String> property, Local<Value> value, const Nan::PropertyCallbackInfo<void> &info) {
      HandleScope scope;

      if (!NodeRT::Utils::IsRect(value)) {
        Nan::ThrowError(Nan::Error(NodeRT::Utils::NewString(L"Value to set is of unexpected type")));
        return;
      }

      if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::Data::Pdf::PdfPageRenderOptions^>(info.This())) {
        return;
      }

      PdfPageRenderOptions *wrapper = PdfPageRenderOptions::Unwrap<PdfPageRenderOptions>(info.This());

      try {

        ::Windows::Foundation::Rect winRtValue = NodeRT::Utils::RectFromJs(value);

        wrapper->_instance->SourceRect = winRtValue;
      } catch (Platform::Exception ^exception) {
        NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
      }
    }
      
    static void IsIgnoringHighContrastGetter(Local<String> property, const Nan::PropertyCallbackInfo<v8::Value> &info) {
      HandleScope scope;

      if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::Data::Pdf::PdfPageRenderOptions^>(info.This())) {
        return;
      }

      PdfPageRenderOptions *wrapper = PdfPageRenderOptions::Unwrap<PdfPageRenderOptions>(info.This());

      try  {
        bool result = wrapper->_instance->IsIgnoringHighContrast;
        info.GetReturnValue().Set(Nan::New<Boolean>(result));
        return;
      } catch (Platform::Exception ^exception) {
        NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
        return;
      }
    }
      
    static void IsIgnoringHighContrastSetter(Local<String> property, Local<Value> value, const Nan::PropertyCallbackInfo<void> &info) {
      HandleScope scope;

      if (!value->IsBoolean()) {
        Nan::ThrowError(Nan::Error(NodeRT::Utils::NewString(L"Value to set is of unexpected type")));
        return;
      }

      if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::Data::Pdf::PdfPageRenderOptions^>(info.This())) {
        return;
      }

      PdfPageRenderOptions *wrapper = PdfPageRenderOptions::Unwrap<PdfPageRenderOptions>(info.This());

      try {

        bool winRtValue = Nan::To<bool>(value).FromMaybe(false);

        wrapper->_instance->IsIgnoringHighContrast = winRtValue;
      } catch (Platform::Exception ^exception) {
        NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
      }
    }
      
    static void DestinationWidthGetter(Local<String> property, const Nan::PropertyCallbackInfo<v8::Value> &info) {
      HandleScope scope;

      if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::Data::Pdf::PdfPageRenderOptions^>(info.This())) {
        return;
      }

      PdfPageRenderOptions *wrapper = PdfPageRenderOptions::Unwrap<PdfPageRenderOptions>(info.This());

      try  {
        unsigned int result = wrapper->_instance->DestinationWidth;
        info.GetReturnValue().Set(Nan::New<Integer>(result));
        return;
      } catch (Platform::Exception ^exception) {
        NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
        return;
      }
    }
      
    static void DestinationWidthSetter(Local<String> property, Local<Value> value, const Nan::PropertyCallbackInfo<void> &info) {
      HandleScope scope;

      if (!value->IsUint32()) {
        Nan::ThrowError(Nan::Error(NodeRT::Utils::NewString(L"Value to set is of unexpected type")));
        return;
      }

      if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::Data::Pdf::PdfPageRenderOptions^>(info.This())) {
        return;
      }

      PdfPageRenderOptions *wrapper = PdfPageRenderOptions::Unwrap<PdfPageRenderOptions>(info.This());

      try {

        unsigned int winRtValue = static_cast<unsigned int>(Nan::To<uint32_t>(value).FromMaybe(0));

        wrapper->_instance->DestinationWidth = winRtValue;
      } catch (Platform::Exception ^exception) {
        NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
      }
    }
      
    static void DestinationHeightGetter(Local<String> property, const Nan::PropertyCallbackInfo<v8::Value> &info) {
      HandleScope scope;

      if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::Data::Pdf::PdfPageRenderOptions^>(info.This())) {
        return;
      }

      PdfPageRenderOptions *wrapper = PdfPageRenderOptions::Unwrap<PdfPageRenderOptions>(info.This());

      try  {
        unsigned int result = wrapper->_instance->DestinationHeight;
        info.GetReturnValue().Set(Nan::New<Integer>(result));
        return;
      } catch (Platform::Exception ^exception) {
        NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
        return;
      }
    }
      
    static void DestinationHeightSetter(Local<String> property, Local<Value> value, const Nan::PropertyCallbackInfo<void> &info) {
      HandleScope scope;

      if (!value->IsUint32()) {
        Nan::ThrowError(Nan::Error(NodeRT::Utils::NewString(L"Value to set is of unexpected type")));
        return;
      }

      if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::Data::Pdf::PdfPageRenderOptions^>(info.This())) {
        return;
      }

      PdfPageRenderOptions *wrapper = PdfPageRenderOptions::Unwrap<PdfPageRenderOptions>(info.This());

      try {

        unsigned int winRtValue = static_cast<unsigned int>(Nan::To<uint32_t>(value).FromMaybe(0));

        wrapper->_instance->DestinationHeight = winRtValue;
      } catch (Platform::Exception ^exception) {
        NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
      }
    }
      
    static void BitmapEncoderIdGetter(Local<String> property, const Nan::PropertyCallbackInfo<v8::Value> &info) {
      HandleScope scope;

      if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::Data::Pdf::PdfPageRenderOptions^>(info.This())) {
        return;
      }

      PdfPageRenderOptions *wrapper = PdfPageRenderOptions::Unwrap<PdfPageRenderOptions>(info.This());

      try  {
        ::Platform::Guid result = wrapper->_instance->BitmapEncoderId;
        info.GetReturnValue().Set(NodeRT::Utils::GuidToJs(result));
        return;
      } catch (Platform::Exception ^exception) {
        NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
        return;
      }
    }
      
    static void BitmapEncoderIdSetter(Local<String> property, Local<Value> value, const Nan::PropertyCallbackInfo<void> &info) {
      HandleScope scope;

      if (!NodeRT::Utils::IsGuid(value)) {
        Nan::ThrowError(Nan::Error(NodeRT::Utils::NewString(L"Value to set is of unexpected type")));
        return;
      }

      if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::Data::Pdf::PdfPageRenderOptions^>(info.This())) {
        return;
      }

      PdfPageRenderOptions *wrapper = PdfPageRenderOptions::Unwrap<PdfPageRenderOptions>(info.This());

      try {

        ::Platform::Guid winRtValue = NodeRT::Utils::GuidFromJs(value);

        wrapper->_instance->BitmapEncoderId = winRtValue;
      } catch (Platform::Exception ^exception) {
        NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
      }
    }
      
    static void BackgroundColorGetter(Local<String> property, const Nan::PropertyCallbackInfo<v8::Value> &info) {
      HandleScope scope;

      if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::Data::Pdf::PdfPageRenderOptions^>(info.This())) {
        return;
      }

      PdfPageRenderOptions *wrapper = PdfPageRenderOptions::Unwrap<PdfPageRenderOptions>(info.This());

      try  {
        ::Windows::UI::Color result = wrapper->_instance->BackgroundColor;
        info.GetReturnValue().Set(NodeRT::Utils::ColorToJs(result));
        return;
      } catch (Platform::Exception ^exception) {
        NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
        return;
      }
    }
      
    static void BackgroundColorSetter(Local<String> property, Local<Value> value, const Nan::PropertyCallbackInfo<void> &info) {
      HandleScope scope;

      if (!NodeRT::Utils::IsColor(value)) {
        Nan::ThrowError(Nan::Error(NodeRT::Utils::NewString(L"Value to set is of unexpected type")));
        return;
      }

      if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::Data::Pdf::PdfPageRenderOptions^>(info.This())) {
        return;
      }

      PdfPageRenderOptions *wrapper = PdfPageRenderOptions::Unwrap<PdfPageRenderOptions>(info.This());

      try {

        ::Windows::UI::Color winRtValue = NodeRT::Utils::ColorFromJs(value);

        wrapper->_instance->BackgroundColor = winRtValue;
      } catch (Platform::Exception ^exception) {
        NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
      }
    }
      


    private:
      ::Windows::Data::Pdf::PdfPageRenderOptions^ _instance;
      static Persistent<FunctionTemplate> s_constructorTemplate;

      friend v8::Local<v8::Value> WrapPdfPageRenderOptions(::Windows::Data::Pdf::PdfPageRenderOptions^ wintRtInstance);
      friend ::Windows::Data::Pdf::PdfPageRenderOptions^ UnwrapPdfPageRenderOptions(Local<Value> value);
  };

  Persistent<FunctionTemplate> PdfPageRenderOptions::s_constructorTemplate;

  v8::Local<v8::Value> WrapPdfPageRenderOptions(::Windows::Data::Pdf::PdfPageRenderOptions^ 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>(PdfPageRenderOptions::s_constructorTemplate);
    return scope.Escape(Nan::NewInstance(Nan::GetFunction(localRef).ToLocalChecked(),_countof(args), args).ToLocalChecked());
  }

  ::Windows::Data::Pdf::PdfPageRenderOptions^ UnwrapPdfPageRenderOptions(Local<Value> value) {
     return PdfPageRenderOptions::Unwrap<PdfPageRenderOptions>(Nan::To<Object>(value).ToLocalChecked())->_instance;
  }

  void InitPdfPageRenderOptions(Local<Object> exports) {
    PdfPageRenderOptions::Init(exports);
  }

  class PdfPageDimensions : 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>("PdfPageDimensions").ToLocalChecked());
        localRef->InstanceTemplate()->SetInternalFieldCount(1);





          
            Nan::SetAccessor(localRef->PrototypeTemplate(), Nan::New<String>("artBox").ToLocalChecked(), ArtBoxGetter);
            Nan::SetAccessor(localRef->PrototypeTemplate(), Nan::New<String>("bleedBox").ToLocalChecked(), BleedBoxGetter);
            Nan::SetAccessor(localRef->PrototypeTemplate(), Nan::New<String>("cropBox").ToLocalChecked(), CropBoxGetter);
            Nan::SetAccessor(localRef->PrototypeTemplate(), Nan::New<String>("mediaBox").ToLocalChecked(), MediaBoxGetter);
            Nan::SetAccessor(localRef->PrototypeTemplate(), Nan::New<String>("trimBox").ToLocalChecked(), TrimBoxGetter);

        Local<Object> constructor = Nan::To<Object>(Nan::GetFunction(localRef).ToLocalChecked()).ToLocalChecked();
        Nan::SetMethod(constructor, "castFrom", CastFrom);



        Nan::Set(exports, Nan::New<String>("PdfPageDimensions").ToLocalChecked(), constructor);
      }

      virtual ::Platform::Object^ GetObjectInstance() const override {
        return _instance;
      }

    private:

      PdfPageDimensions(::Windows::Data::Pdf::PdfPageDimensions^ 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::Data::Pdf::PdfPageDimensions^ winRtInstance;


      if (info.Length() == 1 && OpaqueWrapper::IsOpaqueWrapper(info[0]) &&
        NodeRT::Utils::IsWinRtWrapperOf<::Windows::Data::Pdf::PdfPageDimensions^>(info[0])) {
        try {
          winRtInstance = (::Windows::Data::Pdf::PdfPageDimensions^) 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());

      PdfPageDimensions *wrapperInstance = new PdfPageDimensions(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::Data::Pdf::PdfPageDimensions^>(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::Data::Pdf::PdfPageDimensions^ winRtInstance;
      try {
        winRtInstance = (::Windows::Data::Pdf::PdfPageDimensions^) NodeRT::Utils::GetObjectInstance(info[0]);
      } catch (Platform::Exception ^exception) {
        NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
        return;
      }

      info.GetReturnValue().Set(WrapPdfPageDimensions(winRtInstance));
    }





    static void ArtBoxGetter(Local<String> property, const Nan::PropertyCallbackInfo<v8::Value> &info) {
      HandleScope scope;

      if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::Data::Pdf::PdfPageDimensions^>(info.This())) {
        return;
      }

      PdfPageDimensions *wrapper = PdfPageDimensions::Unwrap<PdfPageDimensions>(info.This());

      try  {
        ::Windows::Foundation::Rect result = wrapper->_instance->ArtBox;
        info.GetReturnValue().Set(NodeRT::Utils::RectToJs(result));
        return;
      } catch (Platform::Exception ^exception) {
        NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
        return;
      }
    }
      
    static void BleedBoxGetter(Local<String> property, const Nan::PropertyCallbackInfo<v8::Value> &info) {
      HandleScope scope;

      if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::Data::Pdf::PdfPageDimensions^>(info.This())) {
        return;
      }

      PdfPageDimensions *wrapper = PdfPageDimensions::Unwrap<PdfPageDimensions>(info.This());

      try  {
        ::Windows::Foundation::Rect result = wrapper->_instance->BleedBox;
        info.GetReturnValue().Set(NodeRT::Utils::RectToJs(result));
        return;
      } catch (Platform::Exception ^exception) {
        NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
        return;
      }
    }
      
    static void CropBoxGetter(Local<String> property, const Nan::PropertyCallbackInfo<v8::Value> &info) {
      HandleScope scope;

      if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::Data::Pdf::PdfPageDimensions^>(info.This())) {
        return;
      }

      PdfPageDimensions *wrapper = PdfPageDimensions::Unwrap<PdfPageDimensions>(info.This());

      try  {
        ::Windows::Foundation::Rect result = wrapper->_instance->CropBox;
        info.GetReturnValue().Set(NodeRT::Utils::RectToJs(result));
        return;
      } catch (Platform::Exception ^exception) {
        NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
        return;
      }
    }
      
    static void MediaBoxGetter(Local<String> property, const Nan::PropertyCallbackInfo<v8::Value> &info) {
      HandleScope scope;

      if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::Data::Pdf::PdfPageDimensions^>(info.This())) {
        return;
      }

      PdfPageDimensions *wrapper = PdfPageDimensions::Unwrap<PdfPageDimensions>(info.This());

      try  {
        ::Windows::Foundation::Rect result = wrapper->_instance->MediaBox;
        info.GetReturnValue().Set(NodeRT::Utils::RectToJs(result));
        return;
      } catch (Platform::Exception ^exception) {
        NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
        return;
      }
    }
      
    static void TrimBoxGetter(Local<String> property, const Nan::PropertyCallbackInfo<v8::Value> &info) {
      HandleScope scope;

      if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::Data::Pdf::PdfPageDimensions^>(info.This())) {
        return;
      }

      PdfPageDimensions *wrapper = PdfPageDimensions::Unwrap<PdfPageDimensions>(info.This());

      try  {
        ::Windows::Foundation::Rect result = wrapper->_instance->TrimBox;
        info.GetReturnValue().Set(NodeRT::Utils::RectToJs(result));
        return;
      } catch (Platform::Exception ^exception) {
        NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
        return;
      }
    }
      


    private:
      ::Windows::Data::Pdf::PdfPageDimensions^ _instance;
      static Persistent<FunctionTemplate> s_constructorTemplate;

      friend v8::Local<v8::Value> WrapPdfPageDimensions(::Windows::Data::Pdf::PdfPageDimensions^ wintRtInstance);
      friend ::Windows::Data::Pdf::PdfPageDimensions^ UnwrapPdfPageDimensions(Local<Value> value);
  };

  Persistent<FunctionTemplate> PdfPageDimensions::s_constructorTemplate;

  v8::Local<v8::Value> WrapPdfPageDimensions(::Windows::Data::Pdf::PdfPageDimensions^ 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>(PdfPageDimensions::s_constructorTemplate);
    return scope.Escape(Nan::NewInstance(Nan::GetFunction(localRef).ToLocalChecked(),_countof(args), args).ToLocalChecked());
  }

  ::Windows::Data::Pdf::PdfPageDimensions^ UnwrapPdfPageDimensions(Local<Value> value) {
     return PdfPageDimensions::Unwrap<PdfPageDimensions>(Nan::To<Object>(value).ToLocalChecked())->_instance;
  }

  void InitPdfPageDimensions(Local<Object> exports) {
    PdfPageDimensions::Init(exports);
  }

  class PdfPage : 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>("PdfPage").ToLocalChecked());
        localRef->InstanceTemplate()->SetInternalFieldCount(1);

        Local<Function> func;
        Local<FunctionTemplate> funcTemplate;

          
            Nan::SetPrototypeMethod(localRef, "close", Close);
          

          
            Nan::SetPrototypeMethod(localRef, "renderToStreamAsync", RenderToStreamAsync);
            Nan::SetPrototypeMethod(localRef, "preparePageAsync", PreparePageAsync);
          


          
            Nan::SetAccessor(localRef->PrototypeTemplate(), Nan::New<String>("dimensions").ToLocalChecked(), DimensionsGetter);
            Nan::SetAccessor(localRef->PrototypeTemplate(), Nan::New<String>("index").ToLocalChecked(), IndexGetter);
            Nan::SetAccessor(localRef->PrototypeTemplate(), Nan::New<String>("preferredZoom").ToLocalChecked(), PreferredZoomGetter);
            Nan::SetAccessor(localRef->PrototypeTemplate(), Nan::New<String>("rotation").ToLocalChecked(), RotationGetter);
            Nan::SetAccessor(localRef->PrototypeTemplate(), Nan::New<String>("size").ToLocalChecked(), SizeGetter);

        Local<Object> constructor = Nan::To<Object>(Nan::GetFunction(localRef).ToLocalChecked()).ToLocalChecked();
        Nan::SetMethod(constructor, "castFrom", CastFrom);



        Nan::Set(exports, Nan::New<String>("PdfPage").ToLocalChecked(), constructor);
      }

      virtual ::Platform::Object^ GetObjectInstance() const override {
        return _instance;
      }

    private:

      PdfPage(::Windows::Data::Pdf::PdfPage^ 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::Data::Pdf::PdfPage^ winRtInstance;


      if (info.Length() == 1 && OpaqueWrapper::IsOpaqueWrapper(info[0]) &&
        NodeRT::Utils::IsWinRtWrapperOf<::Windows::Data::Pdf::PdfPage^>(info[0])) {
        try {
          winRtInstance = (::Windows::Data::Pdf::PdfPage^) 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());

      PdfPage *wrapperInstance = new PdfPage(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::Data::Pdf::PdfPage^>(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::Data::Pdf::PdfPage^ winRtInstance;
      try {
        winRtInstance = (::Windows::Data::Pdf::PdfPage^) NodeRT::Utils::GetObjectInstance(info[0]);
      } catch (Platform::Exception ^exception) {
        NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
        return;
      }

      info.GetReturnValue().Set(WrapPdfPage(winRtInstance));
    }

    static void RenderToStreamAsync(Nan::NAN_METHOD_ARGS_TYPE info) {
      HandleScope scope;

      if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::Data::Pdf::PdfPage^>(info.This())) {
        return;
      }

      if (info.Length() == 0 || !info[info.Length() -1]->IsFunction()) {
        Nan::ThrowError(Nan::Error(NodeRT::Utils::NewString(L"Bad arguments: No callback was given")));
        return;
      }

      PdfPage *wrapper = PdfPage::Unwrap<PdfPage>(info.This());

      ::Windows::Foundation::IAsyncAction^ op;


      if (info.Length() == 2
        && NodeRT::Utils::IsWinRtWrapperOf<::Windows::Storage::Streams::IRandomAccessStream^>(info[0]))
      {
        try
        {
          ::Windows::Storage::Streams::IRandomAccessStream^ arg0 = dynamic_cast<::Windows::Storage::Streams::IRandomAccessStream^>(NodeRT::Utils::GetObjectInstance(info[0]));
          
          op = wrapper->_instance->RenderToStreamAsync(arg0);
        }
        catch (Platform::Exception ^exception)
        {
          NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
          return;
        }
      }
      else if (info.Length() == 3
        && NodeRT::Utils::IsWinRtWrapperOf<::Windows::Storage::Streams::IRandomAccessStream^>(info[0])
        && NodeRT::Utils::IsWinRtWrapperOf<::Windows::Data::Pdf::PdfPageRenderOptions^>(info[1]))
      {
        try
        {
          ::Windows::Storage::Streams::IRandomAccessStream^ arg0 = dynamic_cast<::Windows::Storage::Streams::IRandomAccessStream^>(NodeRT::Utils::GetObjectInstance(info[0]));
          ::Windows::Data::Pdf::PdfPageRenderOptions^ arg1 = UnwrapPdfPageRenderOptions(info[1]);
          
          op = wrapper->_instance->RenderToStreamAsync(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<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 PreparePageAsync(Nan::NAN_METHOD_ARGS_TYPE info) {
      HandleScope scope;

      if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::Data::Pdf::PdfPage^>(info.This())) {
        return;
      }

      if (info.Length() == 0 || !info[info.Length() -1]->IsFunction()) {
        Nan::ThrowError(Nan::Error(NodeRT::Utils::NewString(L"Bad arguments: No callback was given")));
        return;
      }

      PdfPage *wrapper = PdfPage::Unwrap<PdfPage>(info.This());

      ::Windows::Foundation::IAsyncAction^ op;


      if (info.Length() == 1)
      {
        try
        {
          op = wrapper->_instance->PreparePageAsync();
        }
        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 Close(Nan::NAN_METHOD_ARGS_TYPE info) {
      HandleScope scope;

      if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::Data::Pdf::PdfPage^>(info.This())) {
        return;
      }

      PdfPage *wrapper = PdfPage::Unwrap<PdfPage>(info.This());

      if (info.Length() == 0) {
        try {
          delete wrapper->_instance;
          wrapper->_instance = nullptr;
          return;
        } catch (Platform::Exception ^exception) {
          NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
          return;
        }
      } else {
        Nan::ThrowError(Nan::Error(NodeRT::Utils::NewString(L"Bad arguments: no suitable overload found")));
        return;
      }
    }



    static void DimensionsGetter(Local<String> property, const Nan::PropertyCallbackInfo<v8::Value> &info) {
      HandleScope scope;

      if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::Data::Pdf::PdfPage^>(info.This())) {
        return;
      }

      PdfPage *wrapper = PdfPage::Unwrap<PdfPage>(info.This());

      try  {
        ::Windows::Data::Pdf::PdfPageDimensions^ result = wrapper->_instance->Dimensions;
        info.GetReturnValue().Set(WrapPdfPageDimensions(result));
        return;
      } catch (Platform::Exception ^exception) {
        NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
        return;
      }
    }
      
    static void IndexGetter(Local<String> property, const Nan::PropertyCallbackInfo<v8::Value> &info) {
      HandleScope scope;

      if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::Data::Pdf::PdfPage^>(info.This())) {
        return;
      }

      PdfPage *wrapper = PdfPage::Unwrap<PdfPage>(info.This());

      try  {
        unsigned int result = wrapper->_instance->Index;
        info.GetReturnValue().Set(Nan::New<Integer>(result));
        return;
      } catch (Platform::Exception ^exception) {
        NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
        return;
      }
    }
      
    static void PreferredZoomGetter(Local<String> property, const Nan::PropertyCallbackInfo<v8::Value> &info) {
      HandleScope scope;

      if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::Data::Pdf::PdfPage^>(info.This())) {
        return;
      }

      PdfPage *wrapper = PdfPage::Unwrap<PdfPage>(info.This());

      try  {
        float result = wrapper->_instance->PreferredZoom;
        info.GetReturnValue().Set(Nan::New<Number>(static_cast<double>(result)));
        return;
      } catch (Platform::Exception ^exception) {
        NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
        return;
      }
    }
      
    static void RotationGetter(Local<String> property, const Nan::PropertyCallbackInfo<v8::Value> &info) {
      HandleScope scope;

      if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::Data::Pdf::PdfPage^>(info.This())) {
        return;
      }

      PdfPage *wrapper = PdfPage::Unwrap<PdfPage>(info.This());

      try  {
        ::Windows::Data::Pdf::PdfPageRotation result = wrapper->_instance->Rotation;
        info.GetReturnValue().Set(Nan::New<Integer>(static_cast<int>(result)));
        return;
      } catch (Platform::Exception ^exception) {
        NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
        return;
      }
    }
      
    static void SizeGetter(Local<String> property, const Nan::PropertyCallbackInfo<v8::Value> &info) {
      HandleScope scope;

      if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::Data::Pdf::PdfPage^>(info.This())) {
        return;
      }

      PdfPage *wrapper = PdfPage::Unwrap<PdfPage>(info.This());

      try  {
        ::Windows::Foundation::Size result = wrapper->_instance->Size;
        info.GetReturnValue().Set(NodeRT::Utils::SizeToJs(result));
        return;
      } catch (Platform::Exception ^exception) {
        NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
        return;
      }
    }
      


    private:
      ::Windows::Data::Pdf::PdfPage^ _instance;
      static Persistent<FunctionTemplate> s_constructorTemplate;

      friend v8::Local<v8::Value> WrapPdfPage(::Windows::Data::Pdf::PdfPage^ wintRtInstance);
      friend ::Windows::Data::Pdf::PdfPage^ UnwrapPdfPage(Local<Value> value);
  };

  Persistent<FunctionTemplate> PdfPage::s_constructorTemplate;

  v8::Local<v8::Value> WrapPdfPage(::Windows::Data::Pdf::PdfPage^ 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>(PdfPage::s_constructorTemplate);
    return scope.Escape(Nan::NewInstance(Nan::GetFunction(localRef).ToLocalChecked(),_countof(args), args).ToLocalChecked());
  }

  ::Windows::Data::Pdf::PdfPage^ UnwrapPdfPage(Local<Value> value) {
     return PdfPage::Unwrap<PdfPage>(Nan::To<Object>(value).ToLocalChecked())->_instance;
  }

  void InitPdfPage(Local<Object> exports) {
    PdfPage::Init(exports);
  }

  class PdfDocument : 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>("PdfDocument").ToLocalChecked());
        localRef->InstanceTemplate()->SetInternalFieldCount(1);

        Local<Function> func;
        Local<FunctionTemplate> funcTemplate;

          
            Nan::SetPrototypeMethod(localRef, "getPage", GetPage);
          



          
            Nan::SetAccessor(localRef->PrototypeTemplate(), Nan::New<String>("isPasswordProtected").ToLocalChecked(), IsPasswordProtectedGetter);
            Nan::SetAccessor(localRef->PrototypeTemplate(), Nan::New<String>("pageCount").ToLocalChecked(), PageCountGetter);

        Local<Object> constructor = Nan::To<Object>(Nan::GetFunction(localRef).ToLocalChecked()).ToLocalChecked();
        Nan::SetMethod(constructor, "castFrom", CastFrom);

        func = Nan::GetFunction(Nan::New<FunctionTemplate>(LoadFromFileAsync)).ToLocalChecked();
        Nan::Set(constructor, Nan::New<String>("loadFromFileAsync").ToLocalChecked(), func);
        func = Nan::GetFunction(Nan::New<FunctionTemplate>(LoadFromStreamAsync)).ToLocalChecked();
        Nan::Set(constructor, Nan::New<String>("loadFromStreamAsync").ToLocalChecked(), func);


        Nan::Set(exports, Nan::New<String>("PdfDocument").ToLocalChecked(), constructor);
      }

      virtual ::Platform::Object^ GetObjectInstance() const override {
        return _instance;
      }

    private:

      PdfDocument(::Windows::Data::Pdf::PdfDocument^ 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::Data::Pdf::PdfDocument^ winRtInstance;


      if (info.Length() == 1 && OpaqueWrapper::IsOpaqueWrapper(info[0]) &&
        NodeRT::Utils::IsWinRtWrapperOf<::Windows::Data::Pdf::PdfDocument^>(info[0])) {
        try {
          winRtInstance = (::Windows::Data::Pdf::PdfDocument^) 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());

      PdfDocument *wrapperInstance = new PdfDocument(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::Data::Pdf::PdfDocument^>(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::Data::Pdf::PdfDocument^ winRtInstance;
      try {
        winRtInstance = (::Windows::Data::Pdf::PdfDocument^) NodeRT::Utils::GetObjectInstance(info[0]);
      } catch (Platform::Exception ^exception) {
        NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
        return;
      }

      info.GetReturnValue().Set(WrapPdfDocument(winRtInstance));
    }


    static void GetPage(Nan::NAN_METHOD_ARGS_TYPE info) {
      HandleScope scope;

      if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::Data::Pdf::PdfDocument^>(info.This())) {
        return;
      }

      PdfDocument *wrapper = PdfDocument::Unwrap<PdfDocument>(info.This());

      if (info.Length() == 1
        && info[0]->IsUint32())
      {
        try
        {
          unsigned int arg0 = static_cast<unsigned int>(Nan::To<uint32_t>(info[0]).FromMaybe(0));
          
          ::Windows::Data::Pdf::PdfPage^ result;
          result = wrapper->_instance->GetPage(arg0);
          info.GetReturnValue().Set(WrapPdfPage(result));
          return;
        } catch (Platform::Exception ^exception) {
          NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
          return;
        }
      }
 else {
        Nan::ThrowError(Nan::Error(NodeRT::Utils::NewString(L"Bad arguments: no suitable overload found")));
        return;
      }
    }


    static void LoadFromFileAsync(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::Data::Pdf::PdfDocument^>^ op;


      if (info.Length() == 2
          && NodeRT::Utils::IsWinRtWrapperOf<::Windows::Storage::IStorageFile^>(info[0]))
      {
        try
        {
          ::Windows::Storage::IStorageFile^ arg0 = dynamic_cast<::Windows::Storage::IStorageFile^>(NodeRT::Utils::GetObjectInstance(info[0]));
            
          op = ::Windows::Data::Pdf::PdfDocument::LoadFromFileAsync(arg0);
        } catch (Platform::Exception ^exception) {
            NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
            return;
        }
      }
      else if (info.Length() == 3
          && NodeRT::Utils::IsWinRtWrapperOf<::Windows::Storage::IStorageFile^>(info[0])
          && info[1]->IsString())
      {
        try
        {
          ::Windows::Storage::IStorageFile^ arg0 = dynamic_cast<::Windows::Storage::IStorageFile^>(NodeRT::Utils::GetObjectInstance(info[0]));
          Platform::String^ arg1 = ref new Platform::String(NodeRT::Utils::StringToWchar(v8::String::Value(v8::Isolate::GetCurrent(), info[1])));
            
          op = ::Windows::Data::Pdf::PdfDocument::LoadFromFileAsync(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::Data::Pdf::PdfDocument^> t)
      {
        try {
          auto result = t.get();
          NodeUtils::Async::RunCallbackOnMain(asyncToken, [result](NodeUtils::InvokeCallbackDelegate invokeCallback) {


            Local<Value> error;
            Local<Value> arg1;
            {
              TryCatch tryCatch;
              arg1 = WrapPdfDocument(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 LoadFromStreamAsync(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::Data::Pdf::PdfDocument^>^ op;


      if (info.Length() == 2
          && NodeRT::Utils::IsWinRtWrapperOf<::Windows::Storage::Streams::IRandomAccessStream^>(info[0]))
      {
        try
        {
          ::Windows::Storage::Streams::IRandomAccessStream^ arg0 = dynamic_cast<::Windows::Storage::Streams::IRandomAccessStream^>(NodeRT::Utils::GetObjectInstance(info[0]));
            
          op = ::Windows::Data::Pdf::PdfDocument::LoadFromStreamAsync(arg0);
        } catch (Platform::Exception ^exception) {
            NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
            return;
        }
      }
      else if (info.Length() == 3
          && NodeRT::Utils::IsWinRtWrapperOf<::Windows::Storage::Streams::IRandomAccessStream^>(info[0])
          && info[1]->IsString())
      {
        try
        {
          ::Windows::Storage::Streams::IRandomAccessStream^ arg0 = dynamic_cast<::Windows::Storage::Streams::IRandomAccessStream^>(NodeRT::Utils::GetObjectInstance(info[0]));
          Platform::String^ arg1 = ref new Platform::String(NodeRT::Utils::StringToWchar(v8::String::Value(v8::Isolate::GetCurrent(), info[1])));
            
          op = ::Windows::Data::Pdf::PdfDocument::LoadFromStreamAsync(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::Data::Pdf::PdfDocument^> t)
      {
        try {
          auto result = t.get();
          NodeUtils::Async::RunCallbackOnMain(asyncToken, [result](NodeUtils::InvokeCallbackDelegate invokeCallback) {


            Local<Value> error;
            Local<Value> arg1;
            {
              TryCatch tryCatch;
              arg1 = WrapPdfDocument(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 IsPasswordProtectedGetter(Local<String> property, const Nan::PropertyCallbackInfo<v8::Value> &info) {
      HandleScope scope;

      if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::Data::Pdf::PdfDocument^>(info.This())) {
        return;
      }

      PdfDocument *wrapper = PdfDocument::Unwrap<PdfDocument>(info.This());

      try  {
        bool result = wrapper->_instance->IsPasswordProtected;
        info.GetReturnValue().Set(Nan::New<Boolean>(result));
        return;
      } catch (Platform::Exception ^exception) {
        NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
        return;
      }
    }
      
    static void PageCountGetter(Local<String> property, const Nan::PropertyCallbackInfo<v8::Value> &info) {
      HandleScope scope;

      if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::Data::Pdf::PdfDocument^>(info.This())) {
        return;
      }

      PdfDocument *wrapper = PdfDocument::Unwrap<PdfDocument>(info.This());

      try  {
        unsigned int result = wrapper->_instance->PageCount;
        info.GetReturnValue().Set(Nan::New<Integer>(result));
        return;
      } catch (Platform::Exception ^exception) {
        NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
        return;
      }
    }
      


    private:
      ::Windows::Data::Pdf::PdfDocument^ _instance;
      static Persistent<FunctionTemplate> s_constructorTemplate;

      friend v8::Local<v8::Value> WrapPdfDocument(::Windows::Data::Pdf::PdfDocument^ wintRtInstance);
      friend ::Windows::Data::Pdf::PdfDocument^ UnwrapPdfDocument(Local<Value> value);
  };

  Persistent<FunctionTemplate> PdfDocument::s_constructorTemplate;

  v8::Local<v8::Value> WrapPdfDocument(::Windows::Data::Pdf::PdfDocument^ 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>(PdfDocument::s_constructorTemplate);
    return scope.Escape(Nan::NewInstance(Nan::GetFunction(localRef).ToLocalChecked(),_countof(args), args).ToLocalChecked());
  }

  ::Windows::Data::Pdf::PdfDocument^ UnwrapPdfDocument(Local<Value> value) {
     return PdfDocument::Unwrap<PdfDocument>(Nan::To<Object>(value).ToLocalChecked())->_instance;
  }

  void InitPdfDocument(Local<Object> exports) {
    PdfDocument::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::Data::Pdf::InitPdfPageRotationEnum(target);
      NodeRT::Windows::Data::Pdf::InitPdfPageRenderOptions(target);
      NodeRT::Windows::Data::Pdf::InitPdfPageDimensions(target);
      NodeRT::Windows::Data::Pdf::InitPdfPage(target);
      NodeRT::Windows::Data::Pdf::InitPdfDocument(target);


  NodeRT::Utils::RegisterNameSpace("Windows.Data.Pdf", target);
}



NODE_MODULE(binding, init)
