// 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 Web { 
  v8::Local<v8::Value> WrapIUriToStreamResolver(::Windows::Web::IUriToStreamResolver^ wintRtInstance);
  ::Windows::Web::IUriToStreamResolver^ UnwrapIUriToStreamResolver(Local<Value> value);
  
  v8::Local<v8::Value> WrapWebError(::Windows::Web::WebError^ wintRtInstance);
  ::Windows::Web::WebError^ UnwrapWebError(Local<Value> value);
  



  static void InitWebErrorStatusEnum(const Local<Object> exports) {
    HandleScope scope;

    Local<Object> enumObject = Nan::New<Object>();

    Nan::Set(exports, Nan::New<String>("WebErrorStatus").ToLocalChecked(), enumObject);
    Nan::Set(enumObject, Nan::New<String>("unknown").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::Web::WebErrorStatus::Unknown)));
    Nan::Set(enumObject, Nan::New<String>("certificateCommonNameIsIncorrect").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::Web::WebErrorStatus::CertificateCommonNameIsIncorrect)));
    Nan::Set(enumObject, Nan::New<String>("certificateExpired").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::Web::WebErrorStatus::CertificateExpired)));
    Nan::Set(enumObject, Nan::New<String>("certificateContainsErrors").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::Web::WebErrorStatus::CertificateContainsErrors)));
    Nan::Set(enumObject, Nan::New<String>("certificateRevoked").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::Web::WebErrorStatus::CertificateRevoked)));
    Nan::Set(enumObject, Nan::New<String>("certificateIsInvalid").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::Web::WebErrorStatus::CertificateIsInvalid)));
    Nan::Set(enumObject, Nan::New<String>("serverUnreachable").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::Web::WebErrorStatus::ServerUnreachable)));
    Nan::Set(enumObject, Nan::New<String>("timeout").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::Web::WebErrorStatus::Timeout)));
    Nan::Set(enumObject, Nan::New<String>("errorHttpInvalidServerResponse").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::Web::WebErrorStatus::ErrorHttpInvalidServerResponse)));
    Nan::Set(enumObject, Nan::New<String>("connectionAborted").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::Web::WebErrorStatus::ConnectionAborted)));
    Nan::Set(enumObject, Nan::New<String>("connectionReset").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::Web::WebErrorStatus::ConnectionReset)));
    Nan::Set(enumObject, Nan::New<String>("disconnected").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::Web::WebErrorStatus::Disconnected)));
    Nan::Set(enumObject, Nan::New<String>("httpToHttpsOnRedirection").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::Web::WebErrorStatus::HttpToHttpsOnRedirection)));
    Nan::Set(enumObject, Nan::New<String>("httpsToHttpOnRedirection").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::Web::WebErrorStatus::HttpsToHttpOnRedirection)));
    Nan::Set(enumObject, Nan::New<String>("cannotConnect").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::Web::WebErrorStatus::CannotConnect)));
    Nan::Set(enumObject, Nan::New<String>("hostNameNotResolved").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::Web::WebErrorStatus::HostNameNotResolved)));
    Nan::Set(enumObject, Nan::New<String>("operationCanceled").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::Web::WebErrorStatus::OperationCanceled)));
    Nan::Set(enumObject, Nan::New<String>("redirectFailed").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::Web::WebErrorStatus::RedirectFailed)));
    Nan::Set(enumObject, Nan::New<String>("unexpectedStatusCode").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::Web::WebErrorStatus::UnexpectedStatusCode)));
    Nan::Set(enumObject, Nan::New<String>("unexpectedRedirection").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::Web::WebErrorStatus::UnexpectedRedirection)));
    Nan::Set(enumObject, Nan::New<String>("unexpectedClientError").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::Web::WebErrorStatus::UnexpectedClientError)));
    Nan::Set(enumObject, Nan::New<String>("unexpectedServerError").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::Web::WebErrorStatus::UnexpectedServerError)));
    Nan::Set(enumObject, Nan::New<String>("insufficientRangeSupport").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::Web::WebErrorStatus::InsufficientRangeSupport)));
    Nan::Set(enumObject, Nan::New<String>("missingContentLengthSupport").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::Web::WebErrorStatus::MissingContentLengthSupport)));
    Nan::Set(enumObject, Nan::New<String>("multipleChoices").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::Web::WebErrorStatus::MultipleChoices)));
    Nan::Set(enumObject, Nan::New<String>("movedPermanently").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::Web::WebErrorStatus::MovedPermanently)));
    Nan::Set(enumObject, Nan::New<String>("found").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::Web::WebErrorStatus::Found)));
    Nan::Set(enumObject, Nan::New<String>("seeOther").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::Web::WebErrorStatus::SeeOther)));
    Nan::Set(enumObject, Nan::New<String>("notModified").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::Web::WebErrorStatus::NotModified)));
    Nan::Set(enumObject, Nan::New<String>("useProxy").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::Web::WebErrorStatus::UseProxy)));
    Nan::Set(enumObject, Nan::New<String>("temporaryRedirect").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::Web::WebErrorStatus::TemporaryRedirect)));
    Nan::Set(enumObject, Nan::New<String>("badRequest").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::Web::WebErrorStatus::BadRequest)));
    Nan::Set(enumObject, Nan::New<String>("unauthorized").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::Web::WebErrorStatus::Unauthorized)));
    Nan::Set(enumObject, Nan::New<String>("paymentRequired").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::Web::WebErrorStatus::PaymentRequired)));
    Nan::Set(enumObject, Nan::New<String>("forbidden").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::Web::WebErrorStatus::Forbidden)));
    Nan::Set(enumObject, Nan::New<String>("notFound").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::Web::WebErrorStatus::NotFound)));
    Nan::Set(enumObject, Nan::New<String>("methodNotAllowed").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::Web::WebErrorStatus::MethodNotAllowed)));
    Nan::Set(enumObject, Nan::New<String>("notAcceptable").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::Web::WebErrorStatus::NotAcceptable)));
    Nan::Set(enumObject, Nan::New<String>("proxyAuthenticationRequired").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::Web::WebErrorStatus::ProxyAuthenticationRequired)));
    Nan::Set(enumObject, Nan::New<String>("requestTimeout").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::Web::WebErrorStatus::RequestTimeout)));
    Nan::Set(enumObject, Nan::New<String>("conflict").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::Web::WebErrorStatus::Conflict)));
    Nan::Set(enumObject, Nan::New<String>("gone").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::Web::WebErrorStatus::Gone)));
    Nan::Set(enumObject, Nan::New<String>("lengthRequired").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::Web::WebErrorStatus::LengthRequired)));
    Nan::Set(enumObject, Nan::New<String>("preconditionFailed").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::Web::WebErrorStatus::PreconditionFailed)));
    Nan::Set(enumObject, Nan::New<String>("requestEntityTooLarge").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::Web::WebErrorStatus::RequestEntityTooLarge)));
    Nan::Set(enumObject, Nan::New<String>("requestUriTooLong").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::Web::WebErrorStatus::RequestUriTooLong)));
    Nan::Set(enumObject, Nan::New<String>("unsupportedMediaType").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::Web::WebErrorStatus::UnsupportedMediaType)));
    Nan::Set(enumObject, Nan::New<String>("requestedRangeNotSatisfiable").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::Web::WebErrorStatus::RequestedRangeNotSatisfiable)));
    Nan::Set(enumObject, Nan::New<String>("expectationFailed").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::Web::WebErrorStatus::ExpectationFailed)));
    Nan::Set(enumObject, Nan::New<String>("internalServerError").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::Web::WebErrorStatus::InternalServerError)));
    Nan::Set(enumObject, Nan::New<String>("notImplemented").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::Web::WebErrorStatus::NotImplemented)));
    Nan::Set(enumObject, Nan::New<String>("badGateway").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::Web::WebErrorStatus::BadGateway)));
    Nan::Set(enumObject, Nan::New<String>("serviceUnavailable").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::Web::WebErrorStatus::ServiceUnavailable)));
    Nan::Set(enumObject, Nan::New<String>("gatewayTimeout").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::Web::WebErrorStatus::GatewayTimeout)));
    Nan::Set(enumObject, Nan::New<String>("httpVersionNotSupported").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::Web::WebErrorStatus::HttpVersionNotSupported)));
  }



  class IUriToStreamResolver : 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>("IUriToStreamResolver").ToLocalChecked());
        localRef->InstanceTemplate()->SetInternalFieldCount(1);

        Local<Function> func;
        Local<FunctionTemplate> funcTemplate;


          
            Nan::SetPrototypeMethod(localRef, "uriToStreamAsync", UriToStreamAsync);
          



        Local<Object> constructor = Nan::To<Object>(Nan::GetFunction(localRef).ToLocalChecked()).ToLocalChecked();
        Nan::SetMethod(constructor, "castFrom", CastFrom);



        Nan::Set(exports, Nan::New<String>("IUriToStreamResolver").ToLocalChecked(), constructor);
      }

      virtual ::Platform::Object^ GetObjectInstance() const override {
        return _instance;
      }

    private:

      IUriToStreamResolver(::Windows::Web::IUriToStreamResolver^ 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::Web::IUriToStreamResolver^ winRtInstance;


      if (info.Length() == 1 && OpaqueWrapper::IsOpaqueWrapper(info[0]) &&
        NodeRT::Utils::IsWinRtWrapperOf<::Windows::Web::IUriToStreamResolver^>(info[0])) {
        try {
          winRtInstance = (::Windows::Web::IUriToStreamResolver^) 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());

      IUriToStreamResolver *wrapperInstance = new IUriToStreamResolver(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::Web::IUriToStreamResolver^>(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::Web::IUriToStreamResolver^ winRtInstance;
      try {
        winRtInstance = (::Windows::Web::IUriToStreamResolver^) NodeRT::Utils::GetObjectInstance(info[0]);
      } catch (Platform::Exception ^exception) {
        NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
        return;
      }

      info.GetReturnValue().Set(WrapIUriToStreamResolver(winRtInstance));
    }

    static void UriToStreamAsync(Nan::NAN_METHOD_ARGS_TYPE info) {
      HandleScope scope;

      if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::Web::IUriToStreamResolver^>(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;
      }

      IUriToStreamResolver *wrapper = IUriToStreamResolver::Unwrap<IUriToStreamResolver>(info.This());

      ::Windows::Foundation::IAsyncOperation<::Windows::Storage::Streams::IInputStream^>^ op;


      if (info.Length() == 2
        && NodeRT::Utils::IsWinRtWrapperOf<::Windows::Foundation::Uri^>(info[0]))
      {
        try
        {
          ::Windows::Foundation::Uri^ arg0 = dynamic_cast<::Windows::Foundation::Uri^>(NodeRT::Utils::GetObjectInstance(info[0]));
          
          op = wrapper->_instance->UriToStreamAsync(arg0);
        }
        catch (Platform::Exception ^exception)
        {
          NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
          return;
        }
      }
 else {
        Nan::ThrowError(Nan::Error(NodeRT::Utils::NewString(L"Bad arguments: no suitable overload found")));
        return;
      }

      auto opTask = create_task(op);
      uv_async_t* asyncToken = NodeUtils::Async::GetAsyncToken(info[info.Length() -1].As<Function>());

      opTask.then( [asyncToken] (task<::Windows::Storage::Streams::IInputStream^> t) {
        try {
          auto result = t.get();
          NodeUtils::Async::RunCallbackOnMain(asyncToken, [result](NodeUtils::InvokeCallbackDelegate invokeCallback) {


            Local<Value> error;
            Local<Value> arg1;
            {
              TryCatch tryCatch;
              arg1 = NodeRT::Utils::CreateExternalWinRTObject("Windows.Storage.Streams", "IInputStream", 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);
          });
        }
      });
    }






    private:
      ::Windows::Web::IUriToStreamResolver^ _instance;
      static Persistent<FunctionTemplate> s_constructorTemplate;

      friend v8::Local<v8::Value> WrapIUriToStreamResolver(::Windows::Web::IUriToStreamResolver^ wintRtInstance);
      friend ::Windows::Web::IUriToStreamResolver^ UnwrapIUriToStreamResolver(Local<Value> value);
  };

  Persistent<FunctionTemplate> IUriToStreamResolver::s_constructorTemplate;

  v8::Local<v8::Value> WrapIUriToStreamResolver(::Windows::Web::IUriToStreamResolver^ 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>(IUriToStreamResolver::s_constructorTemplate);
    return scope.Escape(Nan::NewInstance(Nan::GetFunction(localRef).ToLocalChecked(),_countof(args), args).ToLocalChecked());
  }

  ::Windows::Web::IUriToStreamResolver^ UnwrapIUriToStreamResolver(Local<Value> value) {
     return IUriToStreamResolver::Unwrap<IUriToStreamResolver>(Nan::To<Object>(value).ToLocalChecked())->_instance;
  }

  void InitIUriToStreamResolver(Local<Object> exports) {
    IUriToStreamResolver::Init(exports);
  }

  class WebError : 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>("WebError").ToLocalChecked());
        localRef->InstanceTemplate()->SetInternalFieldCount(1);






        Local<Object> constructor = Nan::To<Object>(Nan::GetFunction(localRef).ToLocalChecked()).ToLocalChecked();
        Nan::SetMethod(constructor, "castFrom", CastFrom);

        Nan::SetMethod(constructor, "getStatus", GetStatus);


        Nan::Set(exports, Nan::New<String>("WebError").ToLocalChecked(), constructor);
      }

      virtual ::Platform::Object^ GetObjectInstance() const override {
        return _instance;
      }

    private:

      WebError(::Windows::Web::WebError^ 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::Web::WebError^ winRtInstance;


      if (info.Length() == 1 && OpaqueWrapper::IsOpaqueWrapper(info[0]) &&
        NodeRT::Utils::IsWinRtWrapperOf<::Windows::Web::WebError^>(info[0])) {
        try {
          winRtInstance = (::Windows::Web::WebError^) 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());

      WebError *wrapperInstance = new WebError(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::Web::WebError^>(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::Web::WebError^ winRtInstance;
      try {
        winRtInstance = (::Windows::Web::WebError^) NodeRT::Utils::GetObjectInstance(info[0]);
      } catch (Platform::Exception ^exception) {
        NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
        return;
      }

      info.GetReturnValue().Set(WrapWebError(winRtInstance));
    }





    static void GetStatus(Nan::NAN_METHOD_ARGS_TYPE info) {
      HandleScope scope;

      if (info.Length() == 1
        && info[0]->IsInt32())
      {
        try
        {
          int arg0 = static_cast<int>(Nan::To<int32_t>(info[0]).FromMaybe(0));
          
          ::Windows::Web::WebErrorStatus result;
          result = ::Windows::Web::WebError::GetStatus(arg0);
          info.GetReturnValue().Set(Nan::New<Integer>(static_cast<int>(result)));
          return;
        }
        catch (Platform::Exception ^exception)
        {
          NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
          return;
        }
      }
 else  {
        Nan::ThrowError(Nan::Error(NodeRT::Utils::NewString(L"Bad arguments: no suitable overload found")));
        return;
      }
    }



    private:
      ::Windows::Web::WebError^ _instance;
      static Persistent<FunctionTemplate> s_constructorTemplate;

      friend v8::Local<v8::Value> WrapWebError(::Windows::Web::WebError^ wintRtInstance);
      friend ::Windows::Web::WebError^ UnwrapWebError(Local<Value> value);
  };

  Persistent<FunctionTemplate> WebError::s_constructorTemplate;

  v8::Local<v8::Value> WrapWebError(::Windows::Web::WebError^ 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>(WebError::s_constructorTemplate);
    return scope.Escape(Nan::NewInstance(Nan::GetFunction(localRef).ToLocalChecked(),_countof(args), args).ToLocalChecked());
  }

  ::Windows::Web::WebError^ UnwrapWebError(Local<Value> value) {
     return WebError::Unwrap<WebError>(Nan::To<Object>(value).ToLocalChecked())->_instance;
  }

  void InitWebError(Local<Object> exports) {
    WebError::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::Web::InitWebErrorStatusEnum(target);
      NodeRT::Windows::Web::InitIUriToStreamResolver(target);
      NodeRT::Windows::Web::InitWebError(target);


  NodeRT::Utils::RegisterNameSpace("Windows.Web", target);
}



NODE_MODULE(binding, init)
