// 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 Graphics { namespace DirectX { namespace Direct3D11 { 
  v8::Local<v8::Value> WrapIDirect3DDevice(::Windows::Graphics::DirectX::Direct3D11::IDirect3DDevice^ wintRtInstance);
  ::Windows::Graphics::DirectX::Direct3D11::IDirect3DDevice^ UnwrapIDirect3DDevice(Local<Value> value);
  
  v8::Local<v8::Value> WrapIDirect3DSurface(::Windows::Graphics::DirectX::Direct3D11::IDirect3DSurface^ wintRtInstance);
  ::Windows::Graphics::DirectX::Direct3D11::IDirect3DSurface^ UnwrapIDirect3DSurface(Local<Value> value);
  



  static void InitDirect3DUsageEnum(const Local<Object> exports) {
    HandleScope scope;

    Local<Object> enumObject = Nan::New<Object>();

    Nan::Set(exports, Nan::New<String>("Direct3DUsage").ToLocalChecked(), enumObject);
    Nan::Set(enumObject, Nan::New<String>("default").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::Graphics::DirectX::Direct3D11::Direct3DUsage::Default)));
    Nan::Set(enumObject, Nan::New<String>("immutable").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::Graphics::DirectX::Direct3D11::Direct3DUsage::Immutable)));
    Nan::Set(enumObject, Nan::New<String>("dynamic").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::Graphics::DirectX::Direct3D11::Direct3DUsage::Dynamic)));
    Nan::Set(enumObject, Nan::New<String>("staging").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::Graphics::DirectX::Direct3D11::Direct3DUsage::Staging)));
  }

  static void InitDirect3DBindingsEnum(const Local<Object> exports) {
    HandleScope scope;

    Local<Object> enumObject = Nan::New<Object>();

    Nan::Set(exports, Nan::New<String>("Direct3DBindings").ToLocalChecked(), enumObject);
    Nan::Set(enumObject, Nan::New<String>("vertexBuffer").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::Graphics::DirectX::Direct3D11::Direct3DBindings::VertexBuffer)));
    Nan::Set(enumObject, Nan::New<String>("indexBuffer").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::Graphics::DirectX::Direct3D11::Direct3DBindings::IndexBuffer)));
    Nan::Set(enumObject, Nan::New<String>("constantBuffer").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::Graphics::DirectX::Direct3D11::Direct3DBindings::ConstantBuffer)));
    Nan::Set(enumObject, Nan::New<String>("shaderResource").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::Graphics::DirectX::Direct3D11::Direct3DBindings::ShaderResource)));
    Nan::Set(enumObject, Nan::New<String>("streamOutput").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::Graphics::DirectX::Direct3D11::Direct3DBindings::StreamOutput)));
    Nan::Set(enumObject, Nan::New<String>("renderTarget").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::Graphics::DirectX::Direct3D11::Direct3DBindings::RenderTarget)));
    Nan::Set(enumObject, Nan::New<String>("depthStencil").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::Graphics::DirectX::Direct3D11::Direct3DBindings::DepthStencil)));
    Nan::Set(enumObject, Nan::New<String>("unorderedAccess").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::Graphics::DirectX::Direct3D11::Direct3DBindings::UnorderedAccess)));
    Nan::Set(enumObject, Nan::New<String>("decoder").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::Graphics::DirectX::Direct3D11::Direct3DBindings::Decoder)));
    Nan::Set(enumObject, Nan::New<String>("videoEncoder").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::Graphics::DirectX::Direct3D11::Direct3DBindings::VideoEncoder)));
  }

  static bool IsDirect3DMultisampleDescriptionJsObject(Local<Value> value) {
    if (!value->IsObject()) {
      return false;
    }

    Local<String> symbol;
    Local<Object> obj = Nan::To<Object>(value).ToLocalChecked();

    symbol = Nan::New<String>("count").ToLocalChecked();
    if (Nan::Has(obj, symbol).FromMaybe(false)) {
      if (!Nan::Get(obj,symbol).ToLocalChecked()->IsInt32()) {
        return false;
      }
    }
    
    symbol = Nan::New<String>("quality").ToLocalChecked();
    if (Nan::Has(obj, symbol).FromMaybe(false)) {
      if (!Nan::Get(obj,symbol).ToLocalChecked()->IsInt32()) {
        return false;
      }
    }
    
    return true;
  }

  ::Windows::Graphics::DirectX::Direct3D11::Direct3DMultisampleDescription Direct3DMultisampleDescriptionFromJsObject(Local<Value> value) {
    HandleScope scope;
    ::Windows::Graphics::DirectX::Direct3D11::Direct3DMultisampleDescription 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;

    symbol = Nan::New<String>("count").ToLocalChecked();
    if (Nan::Has(obj, symbol).FromMaybe(false)) {
      returnValue.Count = static_cast<int>(Nan::To<int32_t>(Nan::Get(obj,symbol).ToLocalChecked()).FromMaybe(0));
    }
    
    symbol = Nan::New<String>("quality").ToLocalChecked();
    if (Nan::Has(obj, symbol).FromMaybe(false)) {
      returnValue.Quality = static_cast<int>(Nan::To<int32_t>(Nan::Get(obj,symbol).ToLocalChecked()).FromMaybe(0));
    }
    
    return returnValue;
  }

  Local<Value> Direct3DMultisampleDescriptionToJsObject(::Windows::Graphics::DirectX::Direct3D11::Direct3DMultisampleDescription value) {
    EscapableHandleScope scope;

    Local<Object> obj = Nan::New<Object>();

    Nan::Set(obj, Nan::New<String>("count").ToLocalChecked(), Nan::New<Integer>(value.Count));
    Nan::Set(obj, Nan::New<String>("quality").ToLocalChecked(), Nan::New<Integer>(value.Quality));

    return scope.Escape(obj);
  }
  static bool IsDirect3DSurfaceDescriptionJsObject(Local<Value> value) {
    if (!value->IsObject()) {
      return false;
    }

    Local<String> symbol;
    Local<Object> obj = Nan::To<Object>(value).ToLocalChecked();

    symbol = Nan::New<String>("width").ToLocalChecked();
    if (Nan::Has(obj, symbol).FromMaybe(false)) {
      if (!Nan::Get(obj,symbol).ToLocalChecked()->IsInt32()) {
        return false;
      }
    }
    
    symbol = Nan::New<String>("height").ToLocalChecked();
    if (Nan::Has(obj, symbol).FromMaybe(false)) {
      if (!Nan::Get(obj,symbol).ToLocalChecked()->IsInt32()) {
        return false;
      }
    }
    
    symbol = Nan::New<String>("format").ToLocalChecked();
    if (Nan::Has(obj, symbol).FromMaybe(false)) {
      if (!Nan::Get(obj,symbol).ToLocalChecked()->IsInt32()) {
        return false;
      }
    }
    
    symbol = Nan::New<String>("multisampleDescription").ToLocalChecked();
    if (Nan::Has(obj, symbol).FromMaybe(false)) {
      if (!IsDirect3DMultisampleDescriptionJsObject(Nan::Get(obj,symbol).ToLocalChecked())) {
        return false;
      }
    }
    
    return true;
  }

  ::Windows::Graphics::DirectX::Direct3D11::Direct3DSurfaceDescription Direct3DSurfaceDescriptionFromJsObject(Local<Value> value) {
    HandleScope scope;
    ::Windows::Graphics::DirectX::Direct3D11::Direct3DSurfaceDescription 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;

    symbol = Nan::New<String>("width").ToLocalChecked();
    if (Nan::Has(obj, symbol).FromMaybe(false)) {
      returnValue.Width = static_cast<int>(Nan::To<int32_t>(Nan::Get(obj,symbol).ToLocalChecked()).FromMaybe(0));
    }
    
    symbol = Nan::New<String>("height").ToLocalChecked();
    if (Nan::Has(obj, symbol).FromMaybe(false)) {
      returnValue.Height = static_cast<int>(Nan::To<int32_t>(Nan::Get(obj,symbol).ToLocalChecked()).FromMaybe(0));
    }
    
    symbol = Nan::New<String>("format").ToLocalChecked();
    if (Nan::Has(obj, symbol).FromMaybe(false)) {
      returnValue.Format = static_cast<::Windows::Graphics::DirectX::DirectXPixelFormat>(Nan::To<int32_t>(Nan::Get(obj,symbol).ToLocalChecked()).FromMaybe(0));
    }
    
    symbol = Nan::New<String>("multisampleDescription").ToLocalChecked();
    if (Nan::Has(obj, symbol).FromMaybe(false)) {
      returnValue.MultisampleDescription = Direct3DMultisampleDescriptionFromJsObject(Nan::Get(obj,symbol).ToLocalChecked());
    }
    
    return returnValue;
  }

  Local<Value> Direct3DSurfaceDescriptionToJsObject(::Windows::Graphics::DirectX::Direct3D11::Direct3DSurfaceDescription value) {
    EscapableHandleScope scope;

    Local<Object> obj = Nan::New<Object>();

    Nan::Set(obj, Nan::New<String>("width").ToLocalChecked(), Nan::New<Integer>(value.Width));
    Nan::Set(obj, Nan::New<String>("height").ToLocalChecked(), Nan::New<Integer>(value.Height));
    Nan::Set(obj, Nan::New<String>("format").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(value.Format)));
    Nan::Set(obj, Nan::New<String>("multisampleDescription").ToLocalChecked(), Direct3DMultisampleDescriptionToJsObject(value.MultisampleDescription));

    return scope.Escape(obj);
  }


  class IDirect3DDevice : 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>("IDirect3DDevice").ToLocalChecked());
        localRef->InstanceTemplate()->SetInternalFieldCount(1);


          
            Nan::SetPrototypeMethod(localRef, "trim", Trim);
          




        Local<Object> constructor = Nan::To<Object>(Nan::GetFunction(localRef).ToLocalChecked()).ToLocalChecked();
        Nan::SetMethod(constructor, "castFrom", CastFrom);



        Nan::Set(exports, Nan::New<String>("IDirect3DDevice").ToLocalChecked(), constructor);
      }

      virtual ::Platform::Object^ GetObjectInstance() const override {
        return _instance;
      }

    private:

      IDirect3DDevice(::Windows::Graphics::DirectX::Direct3D11::IDirect3DDevice^ 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::Graphics::DirectX::Direct3D11::IDirect3DDevice^ winRtInstance;


      if (info.Length() == 1 && OpaqueWrapper::IsOpaqueWrapper(info[0]) &&
        NodeRT::Utils::IsWinRtWrapperOf<::Windows::Graphics::DirectX::Direct3D11::IDirect3DDevice^>(info[0])) {
        try {
          winRtInstance = (::Windows::Graphics::DirectX::Direct3D11::IDirect3DDevice^) 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());

      IDirect3DDevice *wrapperInstance = new IDirect3DDevice(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::Graphics::DirectX::Direct3D11::IDirect3DDevice^>(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::Graphics::DirectX::Direct3D11::IDirect3DDevice^ winRtInstance;
      try {
        winRtInstance = (::Windows::Graphics::DirectX::Direct3D11::IDirect3DDevice^) NodeRT::Utils::GetObjectInstance(info[0]);
      } catch (Platform::Exception ^exception) {
        NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
        return;
      }

      info.GetReturnValue().Set(WrapIDirect3DDevice(winRtInstance));
    }


    static void Trim(Nan::NAN_METHOD_ARGS_TYPE info) {
      HandleScope scope;

      if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::Graphics::DirectX::Direct3D11::IDirect3DDevice^>(info.This())) {
        return;
      }

      IDirect3DDevice *wrapper = IDirect3DDevice::Unwrap<IDirect3DDevice>(info.This());

      if (info.Length() == 0)
      {
        try
        {
          wrapper->_instance->Trim();
          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::Graphics::DirectX::Direct3D11::IDirect3DDevice^ _instance;
      static Persistent<FunctionTemplate> s_constructorTemplate;

      friend v8::Local<v8::Value> WrapIDirect3DDevice(::Windows::Graphics::DirectX::Direct3D11::IDirect3DDevice^ wintRtInstance);
      friend ::Windows::Graphics::DirectX::Direct3D11::IDirect3DDevice^ UnwrapIDirect3DDevice(Local<Value> value);
  };

  Persistent<FunctionTemplate> IDirect3DDevice::s_constructorTemplate;

  v8::Local<v8::Value> WrapIDirect3DDevice(::Windows::Graphics::DirectX::Direct3D11::IDirect3DDevice^ 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>(IDirect3DDevice::s_constructorTemplate);
    return scope.Escape(Nan::NewInstance(Nan::GetFunction(localRef).ToLocalChecked(),_countof(args), args).ToLocalChecked());
  }

  ::Windows::Graphics::DirectX::Direct3D11::IDirect3DDevice^ UnwrapIDirect3DDevice(Local<Value> value) {
     return IDirect3DDevice::Unwrap<IDirect3DDevice>(Nan::To<Object>(value).ToLocalChecked())->_instance;
  }

  void InitIDirect3DDevice(Local<Object> exports) {
    IDirect3DDevice::Init(exports);
  }

  class IDirect3DSurface : 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>("IDirect3DSurface").ToLocalChecked());
        localRef->InstanceTemplate()->SetInternalFieldCount(1);





          
            Nan::SetAccessor(localRef->PrototypeTemplate(), Nan::New<String>("description").ToLocalChecked(), DescriptionGetter);

        Local<Object> constructor = Nan::To<Object>(Nan::GetFunction(localRef).ToLocalChecked()).ToLocalChecked();
        Nan::SetMethod(constructor, "castFrom", CastFrom);



        Nan::Set(exports, Nan::New<String>("IDirect3DSurface").ToLocalChecked(), constructor);
      }

      virtual ::Platform::Object^ GetObjectInstance() const override {
        return _instance;
      }

    private:

      IDirect3DSurface(::Windows::Graphics::DirectX::Direct3D11::IDirect3DSurface^ 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::Graphics::DirectX::Direct3D11::IDirect3DSurface^ winRtInstance;


      if (info.Length() == 1 && OpaqueWrapper::IsOpaqueWrapper(info[0]) &&
        NodeRT::Utils::IsWinRtWrapperOf<::Windows::Graphics::DirectX::Direct3D11::IDirect3DSurface^>(info[0])) {
        try {
          winRtInstance = (::Windows::Graphics::DirectX::Direct3D11::IDirect3DSurface^) 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());

      IDirect3DSurface *wrapperInstance = new IDirect3DSurface(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::Graphics::DirectX::Direct3D11::IDirect3DSurface^>(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::Graphics::DirectX::Direct3D11::IDirect3DSurface^ winRtInstance;
      try {
        winRtInstance = (::Windows::Graphics::DirectX::Direct3D11::IDirect3DSurface^) NodeRT::Utils::GetObjectInstance(info[0]);
      } catch (Platform::Exception ^exception) {
        NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
        return;
      }

      info.GetReturnValue().Set(WrapIDirect3DSurface(winRtInstance));
    }





    static void DescriptionGetter(Local<String> property, const Nan::PropertyCallbackInfo<v8::Value> &info) {
      HandleScope scope;

      if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::Graphics::DirectX::Direct3D11::IDirect3DSurface^>(info.This())) {
        return;
      }

      IDirect3DSurface *wrapper = IDirect3DSurface::Unwrap<IDirect3DSurface>(info.This());

      try  {
        ::Windows::Graphics::DirectX::Direct3D11::Direct3DSurfaceDescription result = wrapper->_instance->Description;
        info.GetReturnValue().Set(Direct3DSurfaceDescriptionToJsObject(result));
        return;
      } catch (Platform::Exception ^exception) {
        NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
        return;
      }
    }
      


    private:
      ::Windows::Graphics::DirectX::Direct3D11::IDirect3DSurface^ _instance;
      static Persistent<FunctionTemplate> s_constructorTemplate;

      friend v8::Local<v8::Value> WrapIDirect3DSurface(::Windows::Graphics::DirectX::Direct3D11::IDirect3DSurface^ wintRtInstance);
      friend ::Windows::Graphics::DirectX::Direct3D11::IDirect3DSurface^ UnwrapIDirect3DSurface(Local<Value> value);
  };

  Persistent<FunctionTemplate> IDirect3DSurface::s_constructorTemplate;

  v8::Local<v8::Value> WrapIDirect3DSurface(::Windows::Graphics::DirectX::Direct3D11::IDirect3DSurface^ 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>(IDirect3DSurface::s_constructorTemplate);
    return scope.Escape(Nan::NewInstance(Nan::GetFunction(localRef).ToLocalChecked(),_countof(args), args).ToLocalChecked());
  }

  ::Windows::Graphics::DirectX::Direct3D11::IDirect3DSurface^ UnwrapIDirect3DSurface(Local<Value> value) {
     return IDirect3DSurface::Unwrap<IDirect3DSurface>(Nan::To<Object>(value).ToLocalChecked())->_instance;
  }

  void InitIDirect3DSurface(Local<Object> exports) {
    IDirect3DSurface::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::Graphics::DirectX::Direct3D11::InitDirect3DUsageEnum(target);
      NodeRT::Windows::Graphics::DirectX::Direct3D11::InitDirect3DBindingsEnum(target);
      NodeRT::Windows::Graphics::DirectX::Direct3D11::InitIDirect3DDevice(target);
      NodeRT::Windows::Graphics::DirectX::Direct3D11::InitIDirect3DSurface(target);


  NodeRT::Utils::RegisterNameSpace("Windows.Graphics.DirectX.Direct3D11", target);
}



NODE_MODULE(binding, init)
