// Copyright (c) Microsoft Corporation
// All rights reserved. 
//
// Licensed under the Apache License, Version 2.0 (the ""License""); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 
//
// THIS CODE IS PROVIDED ON AN  *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, MERCHANTABLITY OR NON-INFRINGEMENT. 
//
// See the Apache Version 2.0 License for specific language governing permissions and limitations under the License.

#define NTDDI_VERSION 0x06010000

#include <v8.h>
#include <string>
#include <node_object_wrap.h>
#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 namespace v8;
using namespace node;
using namespace concurrency;

namespace NodeRT { namespace Windows { namespace Data { namespace Pdf { 
  v8::Handle<v8::Value> WrapPdfPageRenderOptions(::Windows::Data::Pdf::PdfPageRenderOptions^ wintRtInstance);
  ::Windows::Data::Pdf::PdfPageRenderOptions^ UnwrapPdfPageRenderOptions(Handle<Value> value);
  
  v8::Handle<v8::Value> WrapPdfPageDimensions(::Windows::Data::Pdf::PdfPageDimensions^ wintRtInstance);
  ::Windows::Data::Pdf::PdfPageDimensions^ UnwrapPdfPageDimensions(Handle<Value> value);
  
  v8::Handle<v8::Value> WrapPdfPage(::Windows::Data::Pdf::PdfPage^ wintRtInstance);
  ::Windows::Data::Pdf::PdfPage^ UnwrapPdfPage(Handle<Value> value);
  
  v8::Handle<v8::Value> WrapPdfDocument(::Windows::Data::Pdf::PdfDocument^ wintRtInstance);
  ::Windows::Data::Pdf::PdfDocument^ UnwrapPdfDocument(Handle<Value> value);
  


  static v8::Handle<v8::Value> InitPdfPageRotationEnum(const Handle<Object> exports)
  {
    HandleScope scope;
    
    Handle<Object> enumObject = Object::New();
    exports->Set(String::NewSymbol("PdfPageRotation"), enumObject);

    enumObject->Set(String::NewSymbol("normal"), Integer::New(0));
    enumObject->Set(String::NewSymbol("rotate90"), Integer::New(1));
    enumObject->Set(String::NewSymbol("rotate180"), Integer::New(2));
    enumObject->Set(String::NewSymbol("rotate270"), Integer::New(3));

    return scope.Close(Undefined());
  }



  
  static bool IsRectJsObject(Handle<Value> value)
  {
    if (!value->IsObject())
    {
      return false;
    }

    Handle<String> symbol;
    Handle<Object> obj = value.As<Object>();

    return true;
  }

  ::Windows::Foundation::Rect RectFromJsObject(Handle<Value> value)
  {
    HandleScope scope;
    ::Windows::Foundation::Rect returnValue;
    
    if (!value->IsObject())
    {
      ThrowException(Exception::TypeError(NodeRT::Utils::NewString(L"Unexpected type, expected an object")));
      return returnValue;
    }

    Handle<Object> obj = value.As<Object>();
    Handle<String> symbol;

    return returnValue;
  }

  Handle<Value> RectToJsObject(::Windows::Foundation::Rect value)
  {
    HandleScope scope;

    Handle<Object> obj = Object::New();

    
    return scope.Close(obj);
  }

  
  static bool IsColorJsObject(Handle<Value> value)
  {
    if (!value->IsObject())
    {
      return false;
    }

    Handle<String> symbol;
    Handle<Object> obj = value.As<Object>();

    return true;
  }

  ::Windows::UI::Color ColorFromJsObject(Handle<Value> value)
  {
    HandleScope scope;
    ::Windows::UI::Color returnValue;
    
    if (!value->IsObject())
    {
      ThrowException(Exception::TypeError(NodeRT::Utils::NewString(L"Unexpected type, expected an object")));
      return returnValue;
    }

    Handle<Object> obj = value.As<Object>();
    Handle<String> symbol;

    return returnValue;
  }

  Handle<Value> ColorToJsObject(::Windows::UI::Color value)
  {
    HandleScope scope;

    Handle<Object> obj = Object::New();

    
    return scope.Close(obj);
  }

  
  static bool IsSizeJsObject(Handle<Value> value)
  {
    if (!value->IsObject())
    {
      return false;
    }

    Handle<String> symbol;
    Handle<Object> obj = value.As<Object>();

    return true;
  }

  ::Windows::Foundation::Size SizeFromJsObject(Handle<Value> value)
  {
    HandleScope scope;
    ::Windows::Foundation::Size returnValue;
    
    if (!value->IsObject())
    {
      ThrowException(Exception::TypeError(NodeRT::Utils::NewString(L"Unexpected type, expected an object")));
      return returnValue;
    }

    Handle<Object> obj = value.As<Object>();
    Handle<String> symbol;

    return returnValue;
  }

  Handle<Value> SizeToJsObject(::Windows::Foundation::Size value)
  {
    HandleScope scope;

    Handle<Object> obj = Object::New();

    
    return scope.Close(obj);
  }

  
  class PdfPageRenderOptions : public WrapperBase
  {
  public:    
    static v8::Handle<v8::Value> Init(const Handle<Object> exports)
    {
      HandleScope scope;
      
      s_constructorTemplate = Persistent<FunctionTemplate>::New(FunctionTemplate::New(New));
      s_constructorTemplate->SetClassName(String::NewSymbol("PdfPageRenderOptions"));
      s_constructorTemplate->InstanceTemplate()->SetInternalFieldCount(1);
      
                              
      s_constructorTemplate->PrototypeTemplate()->SetAccessor(String::NewSymbol("sourceRect"), SourceRectGetter, SourceRectSetter);
      s_constructorTemplate->PrototypeTemplate()->SetAccessor(String::NewSymbol("isIgnoringHighContrast"), IsIgnoringHighContrastGetter, IsIgnoringHighContrastSetter);
      s_constructorTemplate->PrototypeTemplate()->SetAccessor(String::NewSymbol("destinationWidth"), DestinationWidthGetter, DestinationWidthSetter);
      s_constructorTemplate->PrototypeTemplate()->SetAccessor(String::NewSymbol("destinationHeight"), DestinationHeightGetter, DestinationHeightSetter);
      s_constructorTemplate->PrototypeTemplate()->SetAccessor(String::NewSymbol("bitmapEncoderId"), BitmapEncoderIdGetter, BitmapEncoderIdSetter);
      s_constructorTemplate->PrototypeTemplate()->SetAccessor(String::NewSymbol("backgroundColor"), BackgroundColorGetter, BackgroundColorSetter);
      
      Local<Function> constructor = s_constructorTemplate->GetFunction();


      exports->Set(String::NewSymbol("PdfPageRenderOptions"), constructor);
      return scope.Close(Undefined());
    }


    virtual ::Platform::Object^ GetObjectInstance() const override
    {
      return _instance;
    }

  private:
    
    PdfPageRenderOptions(::Windows::Data::Pdf::PdfPageRenderOptions^ instance)
    {
      _instance = instance;
    }
    
    
    static v8::Handle<v8::Value> New(const v8::Arguments& args)
    {
      HandleScope scope;

      // in case the constructor was called without the new operator
      if (!s_constructorTemplate->HasInstance(args.This()))
      {
        if (args.Length() > 0)
        {
          std::unique_ptr<Handle<Value> []> constructorArgs(new Handle<Value>[args.Length()]);

          Handle<Value> *argsPtr = constructorArgs.get();
          for (int i = 0; i < args.Length(); i++)
          {
            argsPtr[i] = args[i];
          }

          return s_constructorTemplate->GetFunction()->CallAsConstructor(args.Length(), constructorArgs.get());
        }
        else
        {
          return s_constructorTemplate->GetFunction()->CallAsConstructor(args.Length(), nullptr);
        }
      }
      
      ::Windows::Data::Pdf::PdfPageRenderOptions^ winRtInstance;


      if (args.Length() == 1 && OpaqueWrapper::IsOpaqueWrapper(args[0]) &&
        NodeRT::Utils::IsWinRtWrapperOf<::Windows::Data::Pdf::PdfPageRenderOptions^>(args[0]))
      {
        try 
        {
          winRtInstance = (::Windows::Data::Pdf::PdfPageRenderOptions^) NodeRT::Utils::GetObjectInstance(args[0]);
        }
        catch (Platform::Exception ^exception)
        {
          NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
          return scope.Close(Undefined());
        }
      }
      else if (args.Length() == 0)
      {
        try
        {
          winRtInstance = ref new ::Windows::Data::Pdf::PdfPageRenderOptions();
        }
        catch (Platform::Exception ^exception)
        {
          NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
          return scope.Close(Undefined());
        }
      }
      else
      {
        ThrowException(Exception::Error(NodeRT::Utils::NewString(L"Invalid arguments, no suitable constructor found")));
        return scope.Close(Undefined());
      }

      args.This()->SetHiddenValue(String::NewSymbol("__winRtInstance__"), True());

      PdfPageRenderOptions *wrapperInstance = new PdfPageRenderOptions(winRtInstance);
      wrapperInstance->Wrap(args.This());

      return args.This();
    }


  



    static Handle<Value> SourceRectGetter(Local<String> property, const AccessorInfo &info)
    {
      HandleScope scope;
      
      if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::Data::Pdf::PdfPageRenderOptions^>(info.This()))
      {
        return scope.Close(Undefined());
      }

      PdfPageRenderOptions *wrapper = PdfPageRenderOptions::Unwrap<PdfPageRenderOptions>(info.This());

      try 
      {
        ::Windows::Foundation::Rect result = wrapper->_instance->SourceRect;
        return scope.Close(NodeRT::Utils::RectToJs(result));
      }
      catch (Platform::Exception ^exception)
      {
        NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
        return scope.Close(Undefined());
      }
    }
    
    static void SourceRectSetter(Local<String> property, Local<Value> value, const AccessorInfo &info)
    {
      HandleScope scope;
      
      if (!NodeRT::Utils::IsRect(value))
      {
        ThrowException(Exception::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 Handle<Value> IsIgnoringHighContrastGetter(Local<String> property, const AccessorInfo &info)
    {
      HandleScope scope;
      
      if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::Data::Pdf::PdfPageRenderOptions^>(info.This()))
      {
        return scope.Close(Undefined());
      }

      PdfPageRenderOptions *wrapper = PdfPageRenderOptions::Unwrap<PdfPageRenderOptions>(info.This());

      try 
      {
        bool result = wrapper->_instance->IsIgnoringHighContrast;
        return scope.Close(Boolean::New(result));
      }
      catch (Platform::Exception ^exception)
      {
        NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
        return scope.Close(Undefined());
      }
    }
    
    static void IsIgnoringHighContrastSetter(Local<String> property, Local<Value> value, const AccessorInfo &info)
    {
      HandleScope scope;
      
      if (!value->IsBoolean())
      {
        ThrowException(Exception::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 = value->BooleanValue();

        wrapper->_instance->IsIgnoringHighContrast = winRtValue;
      }
      catch (Platform::Exception ^exception)
      {
        NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
      }
    }
    
    static Handle<Value> DestinationWidthGetter(Local<String> property, const AccessorInfo &info)
    {
      HandleScope scope;
      
      if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::Data::Pdf::PdfPageRenderOptions^>(info.This()))
      {
        return scope.Close(Undefined());
      }

      PdfPageRenderOptions *wrapper = PdfPageRenderOptions::Unwrap<PdfPageRenderOptions>(info.This());

      try 
      {
        unsigned int result = wrapper->_instance->DestinationWidth;
        return scope.Close(Integer::New(result));
      }
      catch (Platform::Exception ^exception)
      {
        NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
        return scope.Close(Undefined());
      }
    }
    
    static void DestinationWidthSetter(Local<String> property, Local<Value> value, const AccessorInfo &info)
    {
      HandleScope scope;
      
      if (!value->IsUint32())
      {
        ThrowException(Exception::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>(value->IntegerValue());

        wrapper->_instance->DestinationWidth = winRtValue;
      }
      catch (Platform::Exception ^exception)
      {
        NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
      }
    }
    
    static Handle<Value> DestinationHeightGetter(Local<String> property, const AccessorInfo &info)
    {
      HandleScope scope;
      
      if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::Data::Pdf::PdfPageRenderOptions^>(info.This()))
      {
        return scope.Close(Undefined());
      }

      PdfPageRenderOptions *wrapper = PdfPageRenderOptions::Unwrap<PdfPageRenderOptions>(info.This());

      try 
      {
        unsigned int result = wrapper->_instance->DestinationHeight;
        return scope.Close(Integer::New(result));
      }
      catch (Platform::Exception ^exception)
      {
        NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
        return scope.Close(Undefined());
      }
    }
    
    static void DestinationHeightSetter(Local<String> property, Local<Value> value, const AccessorInfo &info)
    {
      HandleScope scope;
      
      if (!value->IsUint32())
      {
        ThrowException(Exception::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>(value->IntegerValue());

        wrapper->_instance->DestinationHeight = winRtValue;
      }
      catch (Platform::Exception ^exception)
      {
        NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
      }
    }
    
    static Handle<Value> BitmapEncoderIdGetter(Local<String> property, const AccessorInfo &info)
    {
      HandleScope scope;
      
      if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::Data::Pdf::PdfPageRenderOptions^>(info.This()))
      {
        return scope.Close(Undefined());
      }

      PdfPageRenderOptions *wrapper = PdfPageRenderOptions::Unwrap<PdfPageRenderOptions>(info.This());

      try 
      {
        ::Platform::Guid result = wrapper->_instance->BitmapEncoderId;
        return scope.Close(NodeRT::Utils::GuidToJs(result));
      }
      catch (Platform::Exception ^exception)
      {
        NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
        return scope.Close(Undefined());
      }
    }
    
    static void BitmapEncoderIdSetter(Local<String> property, Local<Value> value, const AccessorInfo &info)
    {
      HandleScope scope;
      
      if (!NodeRT::Utils::IsGuid(value))
      {
        ThrowException(Exception::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 Handle<Value> BackgroundColorGetter(Local<String> property, const AccessorInfo &info)
    {
      HandleScope scope;
      
      if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::Data::Pdf::PdfPageRenderOptions^>(info.This()))
      {
        return scope.Close(Undefined());
      }

      PdfPageRenderOptions *wrapper = PdfPageRenderOptions::Unwrap<PdfPageRenderOptions>(info.This());

      try 
      {
        ::Windows::UI::Color result = wrapper->_instance->BackgroundColor;
        return scope.Close(NodeRT::Utils::ColorToJs(result));
      }
      catch (Platform::Exception ^exception)
      {
        NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
        return scope.Close(Undefined());
      }
    }
    
    static void BackgroundColorSetter(Local<String> property, Local<Value> value, const AccessorInfo &info)
    {
      HandleScope scope;
      
      if (!NodeRT::Utils::IsColor(value))
      {
        ThrowException(Exception::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::Handle<v8::Value> WrapPdfPageRenderOptions(::Windows::Data::Pdf::PdfPageRenderOptions^ wintRtInstance);
    friend ::Windows::Data::Pdf::PdfPageRenderOptions^ UnwrapPdfPageRenderOptions(Handle<Value> value);
    friend bool IsPdfPageRenderOptionsWrapper(Handle<Value> value);
  };
  Persistent<FunctionTemplate> PdfPageRenderOptions::s_constructorTemplate;

  v8::Handle<v8::Value> WrapPdfPageRenderOptions(::Windows::Data::Pdf::PdfPageRenderOptions^ winRtInstance)
  {
    HandleScope scope;

    if (winRtInstance == nullptr)
    {
      return scope.Close(Undefined());
    }

    Handle<Object> opaqueWrapper = CreateOpaqueWrapper(winRtInstance);
    Handle<Value> args[] = {opaqueWrapper};
    return scope.Close(PdfPageRenderOptions::s_constructorTemplate->GetFunction()->NewInstance(_countof(args), args));
  }

  ::Windows::Data::Pdf::PdfPageRenderOptions^ UnwrapPdfPageRenderOptions(Handle<Value> value)
  {
     return PdfPageRenderOptions::Unwrap<PdfPageRenderOptions>(value.As<Object>())->_instance;
  }

  void InitPdfPageRenderOptions(Handle<Object> exports)
  {
    PdfPageRenderOptions::Init(exports);
  }

  class PdfPageDimensions : public WrapperBase
  {
  public:    
    static v8::Handle<v8::Value> Init(const Handle<Object> exports)
    {
      HandleScope scope;
      
      s_constructorTemplate = Persistent<FunctionTemplate>::New(FunctionTemplate::New(New));
      s_constructorTemplate->SetClassName(String::NewSymbol("PdfPageDimensions"));
      s_constructorTemplate->InstanceTemplate()->SetInternalFieldCount(1);
      
                              
      s_constructorTemplate->PrototypeTemplate()->SetAccessor(String::NewSymbol("artBox"), ArtBoxGetter);
      s_constructorTemplate->PrototypeTemplate()->SetAccessor(String::NewSymbol("bleedBox"), BleedBoxGetter);
      s_constructorTemplate->PrototypeTemplate()->SetAccessor(String::NewSymbol("cropBox"), CropBoxGetter);
      s_constructorTemplate->PrototypeTemplate()->SetAccessor(String::NewSymbol("mediaBox"), MediaBoxGetter);
      s_constructorTemplate->PrototypeTemplate()->SetAccessor(String::NewSymbol("trimBox"), TrimBoxGetter);
      
      Local<Function> constructor = s_constructorTemplate->GetFunction();


      exports->Set(String::NewSymbol("PdfPageDimensions"), constructor);
      return scope.Close(Undefined());
    }


    virtual ::Platform::Object^ GetObjectInstance() const override
    {
      return _instance;
    }

  private:
    
    PdfPageDimensions(::Windows::Data::Pdf::PdfPageDimensions^ instance)
    {
      _instance = instance;
    }
    
    
    static v8::Handle<v8::Value> New(const v8::Arguments& args)
    {
      HandleScope scope;

      // in case the constructor was called without the new operator
      if (!s_constructorTemplate->HasInstance(args.This()))
      {
        if (args.Length() > 0)
        {
          std::unique_ptr<Handle<Value> []> constructorArgs(new Handle<Value>[args.Length()]);

          Handle<Value> *argsPtr = constructorArgs.get();
          for (int i = 0; i < args.Length(); i++)
          {
            argsPtr[i] = args[i];
          }

          return s_constructorTemplate->GetFunction()->CallAsConstructor(args.Length(), constructorArgs.get());
        }
        else
        {
          return s_constructorTemplate->GetFunction()->CallAsConstructor(args.Length(), nullptr);
        }
      }
      
      ::Windows::Data::Pdf::PdfPageDimensions^ winRtInstance;


      if (args.Length() == 1 && OpaqueWrapper::IsOpaqueWrapper(args[0]) &&
        NodeRT::Utils::IsWinRtWrapperOf<::Windows::Data::Pdf::PdfPageDimensions^>(args[0]))
      {
        try 
        {
          winRtInstance = (::Windows::Data::Pdf::PdfPageDimensions^) NodeRT::Utils::GetObjectInstance(args[0]);
        }
        catch (Platform::Exception ^exception)
        {
          NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
          return scope.Close(Undefined());
        }
      }
      else
      {
        ThrowException(Exception::Error(NodeRT::Utils::NewString(L"Invalid arguments, no suitable constructor found")));
        return scope.Close(Undefined());
      }

      args.This()->SetHiddenValue(String::NewSymbol("__winRtInstance__"), True());

      PdfPageDimensions *wrapperInstance = new PdfPageDimensions(winRtInstance);
      wrapperInstance->Wrap(args.This());

      return args.This();
    }


  



    static Handle<Value> ArtBoxGetter(Local<String> property, const AccessorInfo &info)
    {
      HandleScope scope;
      
      if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::Data::Pdf::PdfPageDimensions^>(info.This()))
      {
        return scope.Close(Undefined());
      }

      PdfPageDimensions *wrapper = PdfPageDimensions::Unwrap<PdfPageDimensions>(info.This());

      try 
      {
        ::Windows::Foundation::Rect result = wrapper->_instance->ArtBox;
        return scope.Close(NodeRT::Utils::RectToJs(result));
      }
      catch (Platform::Exception ^exception)
      {
        NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
        return scope.Close(Undefined());
      }
    }
    
    static Handle<Value> BleedBoxGetter(Local<String> property, const AccessorInfo &info)
    {
      HandleScope scope;
      
      if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::Data::Pdf::PdfPageDimensions^>(info.This()))
      {
        return scope.Close(Undefined());
      }

      PdfPageDimensions *wrapper = PdfPageDimensions::Unwrap<PdfPageDimensions>(info.This());

      try 
      {
        ::Windows::Foundation::Rect result = wrapper->_instance->BleedBox;
        return scope.Close(NodeRT::Utils::RectToJs(result));
      }
      catch (Platform::Exception ^exception)
      {
        NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
        return scope.Close(Undefined());
      }
    }
    
    static Handle<Value> CropBoxGetter(Local<String> property, const AccessorInfo &info)
    {
      HandleScope scope;
      
      if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::Data::Pdf::PdfPageDimensions^>(info.This()))
      {
        return scope.Close(Undefined());
      }

      PdfPageDimensions *wrapper = PdfPageDimensions::Unwrap<PdfPageDimensions>(info.This());

      try 
      {
        ::Windows::Foundation::Rect result = wrapper->_instance->CropBox;
        return scope.Close(NodeRT::Utils::RectToJs(result));
      }
      catch (Platform::Exception ^exception)
      {
        NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
        return scope.Close(Undefined());
      }
    }
    
    static Handle<Value> MediaBoxGetter(Local<String> property, const AccessorInfo &info)
    {
      HandleScope scope;
      
      if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::Data::Pdf::PdfPageDimensions^>(info.This()))
      {
        return scope.Close(Undefined());
      }

      PdfPageDimensions *wrapper = PdfPageDimensions::Unwrap<PdfPageDimensions>(info.This());

      try 
      {
        ::Windows::Foundation::Rect result = wrapper->_instance->MediaBox;
        return scope.Close(NodeRT::Utils::RectToJs(result));
      }
      catch (Platform::Exception ^exception)
      {
        NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
        return scope.Close(Undefined());
      }
    }
    
    static Handle<Value> TrimBoxGetter(Local<String> property, const AccessorInfo &info)
    {
      HandleScope scope;
      
      if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::Data::Pdf::PdfPageDimensions^>(info.This()))
      {
        return scope.Close(Undefined());
      }

      PdfPageDimensions *wrapper = PdfPageDimensions::Unwrap<PdfPageDimensions>(info.This());

      try 
      {
        ::Windows::Foundation::Rect result = wrapper->_instance->TrimBox;
        return scope.Close(NodeRT::Utils::RectToJs(result));
      }
      catch (Platform::Exception ^exception)
      {
        NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
        return scope.Close(Undefined());
      }
    }
    


  private:
    ::Windows::Data::Pdf::PdfPageDimensions^ _instance;
    static Persistent<FunctionTemplate> s_constructorTemplate;

    friend v8::Handle<v8::Value> WrapPdfPageDimensions(::Windows::Data::Pdf::PdfPageDimensions^ wintRtInstance);
    friend ::Windows::Data::Pdf::PdfPageDimensions^ UnwrapPdfPageDimensions(Handle<Value> value);
    friend bool IsPdfPageDimensionsWrapper(Handle<Value> value);
  };
  Persistent<FunctionTemplate> PdfPageDimensions::s_constructorTemplate;

  v8::Handle<v8::Value> WrapPdfPageDimensions(::Windows::Data::Pdf::PdfPageDimensions^ winRtInstance)
  {
    HandleScope scope;

    if (winRtInstance == nullptr)
    {
      return scope.Close(Undefined());
    }

    Handle<Object> opaqueWrapper = CreateOpaqueWrapper(winRtInstance);
    Handle<Value> args[] = {opaqueWrapper};
    return scope.Close(PdfPageDimensions::s_constructorTemplate->GetFunction()->NewInstance(_countof(args), args));
  }

  ::Windows::Data::Pdf::PdfPageDimensions^ UnwrapPdfPageDimensions(Handle<Value> value)
  {
     return PdfPageDimensions::Unwrap<PdfPageDimensions>(value.As<Object>())->_instance;
  }

  void InitPdfPageDimensions(Handle<Object> exports)
  {
    PdfPageDimensions::Init(exports);
  }

  class PdfPage : public WrapperBase
  {
  public:    
    static v8::Handle<v8::Value> Init(const Handle<Object> exports)
    {
      HandleScope scope;
      
      s_constructorTemplate = Persistent<FunctionTemplate>::New(FunctionTemplate::New(New));
      s_constructorTemplate->SetClassName(String::NewSymbol("PdfPage"));
      s_constructorTemplate->InstanceTemplate()->SetInternalFieldCount(1);
      
      Handle<Value> asyncSymbol = String::NewSymbol("__winRtAsync__");
      Handle<Function> func;
            
      s_constructorTemplate->PrototypeTemplate()->Set(String::NewSymbol("close"), FunctionTemplate::New(Close)->GetFunction());
      
            
      func = FunctionTemplate::New(RenderToStreamAsync)->GetFunction();
      func->Set(asyncSymbol, True(), PropertyAttribute::DontEnum);
      s_constructorTemplate->PrototypeTemplate()->Set(String::NewSymbol("renderToStreamAsync"), func);
      func = FunctionTemplate::New(PreparePageAsync)->GetFunction();
      func->Set(asyncSymbol, True(), PropertyAttribute::DontEnum);
      s_constructorTemplate->PrototypeTemplate()->Set(String::NewSymbol("preparePageAsync"), func);
      
                  
      s_constructorTemplate->PrototypeTemplate()->SetAccessor(String::NewSymbol("dimensions"), DimensionsGetter);
      s_constructorTemplate->PrototypeTemplate()->SetAccessor(String::NewSymbol("index"), IndexGetter);
      s_constructorTemplate->PrototypeTemplate()->SetAccessor(String::NewSymbol("preferredZoom"), PreferredZoomGetter);
      s_constructorTemplate->PrototypeTemplate()->SetAccessor(String::NewSymbol("rotation"), RotationGetter);
      s_constructorTemplate->PrototypeTemplate()->SetAccessor(String::NewSymbol("size"), SizeGetter);
      
      Local<Function> constructor = s_constructorTemplate->GetFunction();


      exports->Set(String::NewSymbol("PdfPage"), constructor);
      return scope.Close(Undefined());
    }


    virtual ::Platform::Object^ GetObjectInstance() const override
    {
      return _instance;
    }

  private:
    
    PdfPage(::Windows::Data::Pdf::PdfPage^ instance)
    {
      _instance = instance;
    }
    
    
    static v8::Handle<v8::Value> New(const v8::Arguments& args)
    {
      HandleScope scope;

      // in case the constructor was called without the new operator
      if (!s_constructorTemplate->HasInstance(args.This()))
      {
        if (args.Length() > 0)
        {
          std::unique_ptr<Handle<Value> []> constructorArgs(new Handle<Value>[args.Length()]);

          Handle<Value> *argsPtr = constructorArgs.get();
          for (int i = 0; i < args.Length(); i++)
          {
            argsPtr[i] = args[i];
          }

          return s_constructorTemplate->GetFunction()->CallAsConstructor(args.Length(), constructorArgs.get());
        }
        else
        {
          return s_constructorTemplate->GetFunction()->CallAsConstructor(args.Length(), nullptr);
        }
      }
      
      ::Windows::Data::Pdf::PdfPage^ winRtInstance;


      if (args.Length() == 1 && OpaqueWrapper::IsOpaqueWrapper(args[0]) &&
        NodeRT::Utils::IsWinRtWrapperOf<::Windows::Data::Pdf::PdfPage^>(args[0]))
      {
        try 
        {
          winRtInstance = (::Windows::Data::Pdf::PdfPage^) NodeRT::Utils::GetObjectInstance(args[0]);
        }
        catch (Platform::Exception ^exception)
        {
          NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
          return scope.Close(Undefined());
        }
      }
      else
      {
        ThrowException(Exception::Error(NodeRT::Utils::NewString(L"Invalid arguments, no suitable constructor found")));
        return scope.Close(Undefined());
      }

      args.This()->SetHiddenValue(String::NewSymbol("__winRtInstance__"), True());

      PdfPage *wrapperInstance = new PdfPage(winRtInstance);
      wrapperInstance->Wrap(args.This());

      return args.This();
    }


    static Handle<Value> RenderToStreamAsync(const v8::Arguments& args)
    {
      HandleScope scope;

      if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::Data::Pdf::PdfPage^>(args.This()))
      {
        return scope.Close(Undefined());
      }

      if (args.Length() == 0 || !args[args.Length() -1]->IsFunction())
      {
          ThrowException(Exception::Error(NodeRT::Utils::NewString(L"Bad arguments: No callback was given")));
          return scope.Close(Undefined());
      }

      PdfPage *wrapper = PdfPage::Unwrap<PdfPage>(args.This());

      ::Windows::Foundation::IAsyncAction^ op;
    

      if (args.Length() == 2
        && NodeRT::Utils::IsWinRtWrapperOf<::Windows::Storage::Streams::IRandomAccessStream^>(args[0]))
      {
        try
        {
          ::Windows::Storage::Streams::IRandomAccessStream^ arg0 = dynamic_cast<::Windows::Storage::Streams::IRandomAccessStream^>(NodeRT::Utils::GetObjectInstance(args[0]));
          
          op = wrapper->_instance->RenderToStreamAsync(arg0);
        }
        catch (Platform::Exception ^exception)
        {
          NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
          return scope.Close(Undefined());
        }
      }
      else if (args.Length() == 3
        && NodeRT::Utils::IsWinRtWrapperOf<::Windows::Storage::Streams::IRandomAccessStream^>(args[0])
        && NodeRT::Utils::IsWinRtWrapperOf<::Windows::Data::Pdf::PdfPageRenderOptions^>(args[1]))
      {
        try
        {
          ::Windows::Storage::Streams::IRandomAccessStream^ arg0 = dynamic_cast<::Windows::Storage::Streams::IRandomAccessStream^>(NodeRT::Utils::GetObjectInstance(args[0]));
          ::Windows::Data::Pdf::PdfPageRenderOptions^ arg1 = UnwrapPdfPageRenderOptions(args[1]);
          
          op = wrapper->_instance->RenderToStreamAsync(arg0,arg1);
        }
        catch (Platform::Exception ^exception)
        {
          NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
          return scope.Close(Undefined());
        }
      }
      else 
      {
        ThrowException(Exception::Error(NodeRT::Utils::NewString(L"Bad arguments: no suitable overload found")));
        return scope.Close(Undefined());
      }
    
      auto opTask = create_task(op);
      uv_async_t* asyncToken = NodeUtils::Async::GetAsyncToken(args[args.Length() -1].As<Function>());

      opTask.then( [asyncToken] (task<void> t) 
      {	
        try
        {
          t.get();
          NodeUtils::Async::RunCallbackOnMain(asyncToken, [](NodeUtils::InvokeCallbackDelegate invokeCallback) {


            Handle<Value> args[] = {Undefined()};

            invokeCallback(_countof(args), args);
          });
        }
        catch (Platform::Exception^ exception)
        {
          NodeUtils::Async::RunCallbackOnMain(asyncToken, [exception](NodeUtils::InvokeCallbackDelegate invokeCallback) {
             
            Handle<Value> error = NodeRT::Utils::WinRtExceptionToJsError(exception);
        
            Handle<Value> args[] = {error};
            invokeCallback(_countof(args), args);
          });
        }  		
      });

      return scope.Close(Undefined());
    }
    static Handle<Value> PreparePageAsync(const v8::Arguments& args)
    {
      HandleScope scope;

      if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::Data::Pdf::PdfPage^>(args.This()))
      {
        return scope.Close(Undefined());
      }

      if (args.Length() == 0 || !args[args.Length() -1]->IsFunction())
      {
          ThrowException(Exception::Error(NodeRT::Utils::NewString(L"Bad arguments: No callback was given")));
          return scope.Close(Undefined());
      }

      PdfPage *wrapper = PdfPage::Unwrap<PdfPage>(args.This());

      ::Windows::Foundation::IAsyncAction^ op;
    

      if (args.Length() == 1)
      {
        try
        {
          op = wrapper->_instance->PreparePageAsync();
        }
        catch (Platform::Exception ^exception)
        {
          NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
          return scope.Close(Undefined());
        }
      }
      else 
      {
        ThrowException(Exception::Error(NodeRT::Utils::NewString(L"Bad arguments: no suitable overload found")));
        return scope.Close(Undefined());
      }
    
      auto opTask = create_task(op);
      uv_async_t* asyncToken = NodeUtils::Async::GetAsyncToken(args[args.Length() -1].As<Function>());

      opTask.then( [asyncToken] (task<void> t) 
      {	
        try
        {
          t.get();
          NodeUtils::Async::RunCallbackOnMain(asyncToken, [](NodeUtils::InvokeCallbackDelegate invokeCallback) {


            Handle<Value> args[] = {Undefined()};

            invokeCallback(_countof(args), args);
          });
        }
        catch (Platform::Exception^ exception)
        {
          NodeUtils::Async::RunCallbackOnMain(asyncToken, [exception](NodeUtils::InvokeCallbackDelegate invokeCallback) {
             
            Handle<Value> error = NodeRT::Utils::WinRtExceptionToJsError(exception);
        
            Handle<Value> args[] = {error};
            invokeCallback(_countof(args), args);
          });
        }  		
      });

      return scope.Close(Undefined());
    }
  
    static Handle<Value> Close(const v8::Arguments& args)
    {
      HandleScope scope;

      if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::Data::Pdf::PdfPage^>(args.This()))
      {
        return scope.Close(Undefined());
      }

      PdfPage *wrapper = PdfPage::Unwrap<PdfPage>(args.This());

      if (args.Length() == 0)
      {
        try
        {
          delete wrapper->_instance;
          wrapper->_instance = nullptr;
          return scope.Close(Undefined());   
        }
        catch (Platform::Exception ^exception)
        {
          NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
          return scope.Close(Undefined());
        }
      }
      else 
      {
        ThrowException(Exception::Error(NodeRT::Utils::NewString(L"Bad arguments: no suitable overload found")));
        return scope.Close(Undefined());
      }

      return scope.Close(Undefined());
    }




    static Handle<Value> DimensionsGetter(Local<String> property, const AccessorInfo &info)
    {
      HandleScope scope;
      
      if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::Data::Pdf::PdfPage^>(info.This()))
      {
        return scope.Close(Undefined());
      }

      PdfPage *wrapper = PdfPage::Unwrap<PdfPage>(info.This());

      try 
      {
        ::Windows::Data::Pdf::PdfPageDimensions^ result = wrapper->_instance->Dimensions;
        return scope.Close(WrapPdfPageDimensions(result));
      }
      catch (Platform::Exception ^exception)
      {
        NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
        return scope.Close(Undefined());
      }
    }
    
    static Handle<Value> IndexGetter(Local<String> property, const AccessorInfo &info)
    {
      HandleScope scope;
      
      if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::Data::Pdf::PdfPage^>(info.This()))
      {
        return scope.Close(Undefined());
      }

      PdfPage *wrapper = PdfPage::Unwrap<PdfPage>(info.This());

      try 
      {
        unsigned int result = wrapper->_instance->Index;
        return scope.Close(Integer::New(result));
      }
      catch (Platform::Exception ^exception)
      {
        NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
        return scope.Close(Undefined());
      }
    }
    
    static Handle<Value> PreferredZoomGetter(Local<String> property, const AccessorInfo &info)
    {
      HandleScope scope;
      
      if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::Data::Pdf::PdfPage^>(info.This()))
      {
        return scope.Close(Undefined());
      }

      PdfPage *wrapper = PdfPage::Unwrap<PdfPage>(info.This());

      try 
      {
        float result = wrapper->_instance->PreferredZoom;
        return scope.Close(Number::New(static_cast<double>(result)));
      }
      catch (Platform::Exception ^exception)
      {
        NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
        return scope.Close(Undefined());
      }
    }
    
    static Handle<Value> RotationGetter(Local<String> property, const AccessorInfo &info)
    {
      HandleScope scope;
      
      if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::Data::Pdf::PdfPage^>(info.This()))
      {
        return scope.Close(Undefined());
      }

      PdfPage *wrapper = PdfPage::Unwrap<PdfPage>(info.This());

      try 
      {
        ::Windows::Data::Pdf::PdfPageRotation result = wrapper->_instance->Rotation;
        return scope.Close(Integer::New(static_cast<int>(result)));
      }
      catch (Platform::Exception ^exception)
      {
        NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
        return scope.Close(Undefined());
      }
    }
    
    static Handle<Value> SizeGetter(Local<String> property, const AccessorInfo &info)
    {
      HandleScope scope;
      
      if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::Data::Pdf::PdfPage^>(info.This()))
      {
        return scope.Close(Undefined());
      }

      PdfPage *wrapper = PdfPage::Unwrap<PdfPage>(info.This());

      try 
      {
        ::Windows::Foundation::Size result = wrapper->_instance->Size;
        return scope.Close(NodeRT::Utils::SizeToJs(result));
      }
      catch (Platform::Exception ^exception)
      {
        NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
        return scope.Close(Undefined());
      }
    }
    


  private:
    ::Windows::Data::Pdf::PdfPage^ _instance;
    static Persistent<FunctionTemplate> s_constructorTemplate;

    friend v8::Handle<v8::Value> WrapPdfPage(::Windows::Data::Pdf::PdfPage^ wintRtInstance);
    friend ::Windows::Data::Pdf::PdfPage^ UnwrapPdfPage(Handle<Value> value);
    friend bool IsPdfPageWrapper(Handle<Value> value);
  };
  Persistent<FunctionTemplate> PdfPage::s_constructorTemplate;

  v8::Handle<v8::Value> WrapPdfPage(::Windows::Data::Pdf::PdfPage^ winRtInstance)
  {
    HandleScope scope;

    if (winRtInstance == nullptr)
    {
      return scope.Close(Undefined());
    }

    Handle<Object> opaqueWrapper = CreateOpaqueWrapper(winRtInstance);
    Handle<Value> args[] = {opaqueWrapper};
    return scope.Close(PdfPage::s_constructorTemplate->GetFunction()->NewInstance(_countof(args), args));
  }

  ::Windows::Data::Pdf::PdfPage^ UnwrapPdfPage(Handle<Value> value)
  {
     return PdfPage::Unwrap<PdfPage>(value.As<Object>())->_instance;
  }

  void InitPdfPage(Handle<Object> exports)
  {
    PdfPage::Init(exports);
  }

  class PdfDocument : public WrapperBase
  {
  public:    
    static v8::Handle<v8::Value> Init(const Handle<Object> exports)
    {
      HandleScope scope;
      
      s_constructorTemplate = Persistent<FunctionTemplate>::New(FunctionTemplate::New(New));
      s_constructorTemplate->SetClassName(String::NewSymbol("PdfDocument"));
      s_constructorTemplate->InstanceTemplate()->SetInternalFieldCount(1);
      
      Handle<Value> asyncSymbol = String::NewSymbol("__winRtAsync__");
      Handle<Function> func;
            
      s_constructorTemplate->PrototypeTemplate()->Set(String::NewSymbol("getPage"), FunctionTemplate::New(GetPage)->GetFunction());
      
                        
      s_constructorTemplate->PrototypeTemplate()->SetAccessor(String::NewSymbol("isPasswordProtected"), IsPasswordProtectedGetter);
      s_constructorTemplate->PrototypeTemplate()->SetAccessor(String::NewSymbol("pageCount"), PageCountGetter);
      
      Local<Function> constructor = s_constructorTemplate->GetFunction();

      func = FunctionTemplate::New(LoadFromFileAsync)->GetFunction();
      func->Set(asyncSymbol, True(), PropertyAttribute::DontEnum);
      constructor->Set(String::NewSymbol("loadFromFileAsync"), func);
      func = FunctionTemplate::New(LoadFromStreamAsync)->GetFunction();
      func->Set(asyncSymbol, True(), PropertyAttribute::DontEnum);
      constructor->Set(String::NewSymbol("loadFromStreamAsync"), func);

      exports->Set(String::NewSymbol("PdfDocument"), constructor);
      return scope.Close(Undefined());
    }


    virtual ::Platform::Object^ GetObjectInstance() const override
    {
      return _instance;
    }

  private:
    
    PdfDocument(::Windows::Data::Pdf::PdfDocument^ instance)
    {
      _instance = instance;
    }
    
    
    static v8::Handle<v8::Value> New(const v8::Arguments& args)
    {
      HandleScope scope;

      // in case the constructor was called without the new operator
      if (!s_constructorTemplate->HasInstance(args.This()))
      {
        if (args.Length() > 0)
        {
          std::unique_ptr<Handle<Value> []> constructorArgs(new Handle<Value>[args.Length()]);

          Handle<Value> *argsPtr = constructorArgs.get();
          for (int i = 0; i < args.Length(); i++)
          {
            argsPtr[i] = args[i];
          }

          return s_constructorTemplate->GetFunction()->CallAsConstructor(args.Length(), constructorArgs.get());
        }
        else
        {
          return s_constructorTemplate->GetFunction()->CallAsConstructor(args.Length(), nullptr);
        }
      }
      
      ::Windows::Data::Pdf::PdfDocument^ winRtInstance;


      if (args.Length() == 1 && OpaqueWrapper::IsOpaqueWrapper(args[0]) &&
        NodeRT::Utils::IsWinRtWrapperOf<::Windows::Data::Pdf::PdfDocument^>(args[0]))
      {
        try 
        {
          winRtInstance = (::Windows::Data::Pdf::PdfDocument^) NodeRT::Utils::GetObjectInstance(args[0]);
        }
        catch (Platform::Exception ^exception)
        {
          NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
          return scope.Close(Undefined());
        }
      }
      else
      {
        ThrowException(Exception::Error(NodeRT::Utils::NewString(L"Invalid arguments, no suitable constructor found")));
        return scope.Close(Undefined());
      }

      args.This()->SetHiddenValue(String::NewSymbol("__winRtInstance__"), True());

      PdfDocument *wrapperInstance = new PdfDocument(winRtInstance);
      wrapperInstance->Wrap(args.This());

      return args.This();
    }


  
    static Handle<Value> GetPage(const v8::Arguments& args)
    {
      HandleScope scope;

      if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::Data::Pdf::PdfDocument^>(args.This()))
      {
        return scope.Close(Undefined());
      }

      PdfDocument *wrapper = PdfDocument::Unwrap<PdfDocument>(args.This());

      if (args.Length() == 1
        && args[0]->IsUint32())
      {
        try
        {
          unsigned int arg0 = static_cast<unsigned int>(args[0]->IntegerValue());
          
          ::Windows::Data::Pdf::PdfPage^ result;
          result = wrapper->_instance->GetPage(arg0);
          return scope.Close(WrapPdfPage(result));
        }
        catch (Platform::Exception ^exception)
        {
          NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
          return scope.Close(Undefined());
        }
      }
      else 
      {
        ThrowException(Exception::Error(NodeRT::Utils::NewString(L"Bad arguments: no suitable overload found")));
        return scope.Close(Undefined());
      }

      return scope.Close(Undefined());
    }

    static Handle<Value> LoadFromFileAsync(const v8::Arguments& args)
    {
      HandleScope scope;

      if (args.Length() == 0 || !args[args.Length() -1]->IsFunction())
      {
          ThrowException(Exception::Error(NodeRT::Utils::NewString(L"Bad arguments: No callback was given")));
          return scope.Close(Undefined());
      }

      ::Windows::Foundation::IAsyncOperation<::Windows::Data::Pdf::PdfDocument^>^ op;
      

      if (args.Length() == 2
        && NodeRT::Utils::IsWinRtWrapperOf<::Windows::Storage::IStorageFile^>(args[0]))
      {
        try
        {
          ::Windows::Storage::IStorageFile^ arg0 = dynamic_cast<::Windows::Storage::IStorageFile^>(NodeRT::Utils::GetObjectInstance(args[0]));
          
          op = ::Windows::Data::Pdf::PdfDocument::LoadFromFileAsync(arg0);
        }
        catch (Platform::Exception ^exception)
        {
          NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
          return scope.Close(Undefined());
        }
      }
      else if (args.Length() == 3
        && NodeRT::Utils::IsWinRtWrapperOf<::Windows::Storage::IStorageFile^>(args[0])
        && args[1]->IsString())
      {
        try
        {
          ::Windows::Storage::IStorageFile^ arg0 = dynamic_cast<::Windows::Storage::IStorageFile^>(NodeRT::Utils::GetObjectInstance(args[0]));
          Platform::String^ arg1 = ref new Platform::String(NodeRT::Utils::StringToWchar(v8::String::Value(args[1])));
          
          op = ::Windows::Data::Pdf::PdfDocument::LoadFromFileAsync(arg0,arg1);
        }
        catch (Platform::Exception ^exception)
        {
          NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
          return scope.Close(Undefined());
        }
      }
      else 
      {
        ThrowException(Exception::Error(NodeRT::Utils::NewString(L"Bad arguments: no suitable overload found")));
        return scope.Close(Undefined());
      }
    
      auto opTask = create_task(op);
      uv_async_t* asyncToken = NodeUtils::Async::GetAsyncToken(args[args.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) {

            
            TryCatch tryCatch;
            Handle<Value> error; 
            Handle<Value> arg1 = WrapPdfDocument(result);
            if (tryCatch.HasCaught())
            {
              error = tryCatch.Exception()->ToObject();
            }
            else 
            {
              error = Undefined();
            }
            if (arg1.IsEmpty()) arg1 = Undefined();
            Handle<Value> args[] = {error, arg1};

            invokeCallback(_countof(args), args);
          });
        }
        catch (Platform::Exception^ exception)
        {
          NodeUtils::Async::RunCallbackOnMain(asyncToken, [exception](NodeUtils::InvokeCallbackDelegate invokeCallback) {
          
            Handle<Value> error = NodeRT::Utils::WinRtExceptionToJsError(exception);
        
            Handle<Value> args[] = {error};
            invokeCallback(_countof(args), args);
          });
        }  		
      });

      return scope.Close(Undefined());
    }
    static Handle<Value> LoadFromStreamAsync(const v8::Arguments& args)
    {
      HandleScope scope;

      if (args.Length() == 0 || !args[args.Length() -1]->IsFunction())
      {
          ThrowException(Exception::Error(NodeRT::Utils::NewString(L"Bad arguments: No callback was given")));
          return scope.Close(Undefined());
      }

      ::Windows::Foundation::IAsyncOperation<::Windows::Data::Pdf::PdfDocument^>^ op;
      

      if (args.Length() == 2
        && NodeRT::Utils::IsWinRtWrapperOf<::Windows::Storage::Streams::IRandomAccessStream^>(args[0]))
      {
        try
        {
          ::Windows::Storage::Streams::IRandomAccessStream^ arg0 = dynamic_cast<::Windows::Storage::Streams::IRandomAccessStream^>(NodeRT::Utils::GetObjectInstance(args[0]));
          
          op = ::Windows::Data::Pdf::PdfDocument::LoadFromStreamAsync(arg0);
        }
        catch (Platform::Exception ^exception)
        {
          NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
          return scope.Close(Undefined());
        }
      }
      else if (args.Length() == 3
        && NodeRT::Utils::IsWinRtWrapperOf<::Windows::Storage::Streams::IRandomAccessStream^>(args[0])
        && args[1]->IsString())
      {
        try
        {
          ::Windows::Storage::Streams::IRandomAccessStream^ arg0 = dynamic_cast<::Windows::Storage::Streams::IRandomAccessStream^>(NodeRT::Utils::GetObjectInstance(args[0]));
          Platform::String^ arg1 = ref new Platform::String(NodeRT::Utils::StringToWchar(v8::String::Value(args[1])));
          
          op = ::Windows::Data::Pdf::PdfDocument::LoadFromStreamAsync(arg0,arg1);
        }
        catch (Platform::Exception ^exception)
        {
          NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
          return scope.Close(Undefined());
        }
      }
      else 
      {
        ThrowException(Exception::Error(NodeRT::Utils::NewString(L"Bad arguments: no suitable overload found")));
        return scope.Close(Undefined());
      }
    
      auto opTask = create_task(op);
      uv_async_t* asyncToken = NodeUtils::Async::GetAsyncToken(args[args.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) {

            
            TryCatch tryCatch;
            Handle<Value> error; 
            Handle<Value> arg1 = WrapPdfDocument(result);
            if (tryCatch.HasCaught())
            {
              error = tryCatch.Exception()->ToObject();
            }
            else 
            {
              error = Undefined();
            }
            if (arg1.IsEmpty()) arg1 = Undefined();
            Handle<Value> args[] = {error, arg1};

            invokeCallback(_countof(args), args);
          });
        }
        catch (Platform::Exception^ exception)
        {
          NodeUtils::Async::RunCallbackOnMain(asyncToken, [exception](NodeUtils::InvokeCallbackDelegate invokeCallback) {
          
            Handle<Value> error = NodeRT::Utils::WinRtExceptionToJsError(exception);
        
            Handle<Value> args[] = {error};
            invokeCallback(_countof(args), args);
          });
        }  		
      });

      return scope.Close(Undefined());
    }


    static Handle<Value> IsPasswordProtectedGetter(Local<String> property, const AccessorInfo &info)
    {
      HandleScope scope;
      
      if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::Data::Pdf::PdfDocument^>(info.This()))
      {
        return scope.Close(Undefined());
      }

      PdfDocument *wrapper = PdfDocument::Unwrap<PdfDocument>(info.This());

      try 
      {
        bool result = wrapper->_instance->IsPasswordProtected;
        return scope.Close(Boolean::New(result));
      }
      catch (Platform::Exception ^exception)
      {
        NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
        return scope.Close(Undefined());
      }
    }
    
    static Handle<Value> PageCountGetter(Local<String> property, const AccessorInfo &info)
    {
      HandleScope scope;
      
      if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::Data::Pdf::PdfDocument^>(info.This()))
      {
        return scope.Close(Undefined());
      }

      PdfDocument *wrapper = PdfDocument::Unwrap<PdfDocument>(info.This());

      try 
      {
        unsigned int result = wrapper->_instance->PageCount;
        return scope.Close(Integer::New(result));
      }
      catch (Platform::Exception ^exception)
      {
        NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
        return scope.Close(Undefined());
      }
    }
    


  private:
    ::Windows::Data::Pdf::PdfDocument^ _instance;
    static Persistent<FunctionTemplate> s_constructorTemplate;

    friend v8::Handle<v8::Value> WrapPdfDocument(::Windows::Data::Pdf::PdfDocument^ wintRtInstance);
    friend ::Windows::Data::Pdf::PdfDocument^ UnwrapPdfDocument(Handle<Value> value);
    friend bool IsPdfDocumentWrapper(Handle<Value> value);
  };
  Persistent<FunctionTemplate> PdfDocument::s_constructorTemplate;

  v8::Handle<v8::Value> WrapPdfDocument(::Windows::Data::Pdf::PdfDocument^ winRtInstance)
  {
    HandleScope scope;

    if (winRtInstance == nullptr)
    {
      return scope.Close(Undefined());
    }

    Handle<Object> opaqueWrapper = CreateOpaqueWrapper(winRtInstance);
    Handle<Value> args[] = {opaqueWrapper};
    return scope.Close(PdfDocument::s_constructorTemplate->GetFunction()->NewInstance(_countof(args), args));
  }

  ::Windows::Data::Pdf::PdfDocument^ UnwrapPdfDocument(Handle<Value> value)
  {
     return PdfDocument::Unwrap<PdfDocument>(value.As<Object>())->_instance;
  }

  void InitPdfDocument(Handle<Object> exports)
  {
    PdfDocument::Init(exports);
  }

} } } } 

void init(Handle<Object> exports)
{
  if (FAILED(CoInitializeEx(nullptr, COINIT_MULTITHREADED)))
  {
    ThrowException(v8::Exception::Error(NodeRT::Utils::NewString(L"error in CoInitializeEx()")));
    return;
  }
  
  NodeRT::Windows::Data::Pdf::InitPdfPageRotationEnum(exports);
  NodeRT::Windows::Data::Pdf::InitPdfPageRenderOptions(exports);
  NodeRT::Windows::Data::Pdf::InitPdfPageDimensions(exports);
  NodeRT::Windows::Data::Pdf::InitPdfPage(exports);
  NodeRT::Windows::Data::Pdf::InitPdfDocument(exports);

  NodeRT::Utils::RegisterNameSpace("Windows.Data.Pdf", exports);
}


NODE_MODULE(binding, init)