// 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 System { namespace Threading { 
  v8::Local<v8::Value> WrapThreadPoolTimer(::Windows::System::Threading::ThreadPoolTimer^ wintRtInstance);
  ::Windows::System::Threading::ThreadPoolTimer^ UnwrapThreadPoolTimer(Local<Value> value);
  
  v8::Local<v8::Value> WrapThreadPool(::Windows::System::Threading::ThreadPool^ wintRtInstance);
  ::Windows::System::Threading::ThreadPool^ UnwrapThreadPool(Local<Value> value);
  



  static void InitWorkItemPriorityEnum(const Local<Object> exports) {
    HandleScope scope;

    Local<Object> enumObject = Nan::New<Object>();

    Nan::Set(exports, Nan::New<String>("WorkItemPriority").ToLocalChecked(), enumObject);
    Nan::Set(enumObject, Nan::New<String>("normal").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::System::Threading::WorkItemPriority::Normal)));
    Nan::Set(enumObject, Nan::New<String>("high").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::System::Threading::WorkItemPriority::High)));
    Nan::Set(enumObject, Nan::New<String>("low").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::System::Threading::WorkItemPriority::Low)));
  }

  static void InitWorkItemOptionsEnum(const Local<Object> exports) {
    HandleScope scope;

    Local<Object> enumObject = Nan::New<Object>();

    Nan::Set(exports, Nan::New<String>("WorkItemOptions").ToLocalChecked(), enumObject);
    Nan::Set(enumObject, Nan::New<String>("none").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::System::Threading::WorkItemOptions::None)));
    Nan::Set(enumObject, Nan::New<String>("timeSliced").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::System::Threading::WorkItemOptions::TimeSliced)));
  }



  class ThreadPoolTimer : 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>("ThreadPoolTimer").ToLocalChecked());
        localRef->InstanceTemplate()->SetInternalFieldCount(1);


          
            Nan::SetPrototypeMethod(localRef, "cancel", Cancel);
          



          
            Nan::SetAccessor(localRef->PrototypeTemplate(), Nan::New<String>("delay").ToLocalChecked(), DelayGetter);
            Nan::SetAccessor(localRef->PrototypeTemplate(), Nan::New<String>("period").ToLocalChecked(), PeriodGetter);

        Local<Object> constructor = Nan::To<Object>(Nan::GetFunction(localRef).ToLocalChecked()).ToLocalChecked();
        Nan::SetMethod(constructor, "castFrom", CastFrom);

        Nan::SetMethod(constructor, "createPeriodicTimer", CreatePeriodicTimer);
        Nan::SetMethod(constructor, "createTimer", CreateTimer);


        Nan::Set(exports, Nan::New<String>("ThreadPoolTimer").ToLocalChecked(), constructor);
      }

      virtual ::Platform::Object^ GetObjectInstance() const override {
        return _instance;
      }

    private:

      ThreadPoolTimer(::Windows::System::Threading::ThreadPoolTimer^ 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::System::Threading::ThreadPoolTimer^ winRtInstance;


      if (info.Length() == 1 && OpaqueWrapper::IsOpaqueWrapper(info[0]) &&
        NodeRT::Utils::IsWinRtWrapperOf<::Windows::System::Threading::ThreadPoolTimer^>(info[0])) {
        try {
          winRtInstance = (::Windows::System::Threading::ThreadPoolTimer^) 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());

      ThreadPoolTimer *wrapperInstance = new ThreadPoolTimer(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::System::Threading::ThreadPoolTimer^>(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::System::Threading::ThreadPoolTimer^ winRtInstance;
      try {
        winRtInstance = (::Windows::System::Threading::ThreadPoolTimer^) NodeRT::Utils::GetObjectInstance(info[0]);
      } catch (Platform::Exception ^exception) {
        NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
        return;
      }

      info.GetReturnValue().Set(WrapThreadPoolTimer(winRtInstance));
    }


    static void Cancel(Nan::NAN_METHOD_ARGS_TYPE info) {
      HandleScope scope;

      if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::System::Threading::ThreadPoolTimer^>(info.This())) {
        return;
      }

      ThreadPoolTimer *wrapper = ThreadPoolTimer::Unwrap<ThreadPoolTimer>(info.This());

      if (info.Length() == 0)
      {
        try
        {
          wrapper->_instance->Cancel();
          return;
        } catch (Platform::Exception ^exception) {
          NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
          return;
        }
      }
 else {
        Nan::ThrowError(Nan::Error(NodeRT::Utils::NewString(L"Bad arguments: no suitable overload found")));
        return;
      }
    }



    static void CreatePeriodicTimer(Nan::NAN_METHOD_ARGS_TYPE info) {
      HandleScope scope;

      if (info.Length() == 2
        && NodeRT::Utils::IsWinRtWrapperOf<::Windows::System::Threading::TimerElapsedHandler^>(info[0])
        && info[1]->IsNumber())
      {
        try
        {
          ::Windows::System::Threading::TimerElapsedHandler^ arg0 = dynamic_cast<::Windows::System::Threading::TimerElapsedHandler^>(NodeRT::Utils::GetObjectInstance(info[0]));
          ::Windows::Foundation::TimeSpan arg1 = NodeRT::Utils::TimeSpanFromMilli(Nan::To<int64_t>(info[1]).FromMaybe(0));
          
          ::Windows::System::Threading::ThreadPoolTimer^ result;
          result = ::Windows::System::Threading::ThreadPoolTimer::CreatePeriodicTimer(arg0, arg1);
          info.GetReturnValue().Set(WrapThreadPoolTimer(result));
          return;
        }
        catch (Platform::Exception ^exception)
        {
          NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
          return;
        }
      }
      else if (info.Length() == 3
        && NodeRT::Utils::IsWinRtWrapperOf<::Windows::System::Threading::TimerElapsedHandler^>(info[0])
        && info[1]->IsNumber()
        && NodeRT::Utils::IsWinRtWrapperOf<::Windows::System::Threading::TimerDestroyedHandler^>(info[2]))
      {
        try
        {
          ::Windows::System::Threading::TimerElapsedHandler^ arg0 = dynamic_cast<::Windows::System::Threading::TimerElapsedHandler^>(NodeRT::Utils::GetObjectInstance(info[0]));
          ::Windows::Foundation::TimeSpan arg1 = NodeRT::Utils::TimeSpanFromMilli(Nan::To<int64_t>(info[1]).FromMaybe(0));
          ::Windows::System::Threading::TimerDestroyedHandler^ arg2 = dynamic_cast<::Windows::System::Threading::TimerDestroyedHandler^>(NodeRT::Utils::GetObjectInstance(info[2]));
          
          ::Windows::System::Threading::ThreadPoolTimer^ result;
          result = ::Windows::System::Threading::ThreadPoolTimer::CreatePeriodicTimer(arg0, arg1, arg2);
          info.GetReturnValue().Set(WrapThreadPoolTimer(result));
          return;
        }
        catch (Platform::Exception ^exception)
        {
          NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
          return;
        }
      }
 else  {
        Nan::ThrowError(Nan::Error(NodeRT::Utils::NewString(L"Bad arguments: no suitable overload found")));
        return;
      }
    }

    static void CreateTimer(Nan::NAN_METHOD_ARGS_TYPE info) {
      HandleScope scope;

      if (info.Length() == 2
        && NodeRT::Utils::IsWinRtWrapperOf<::Windows::System::Threading::TimerElapsedHandler^>(info[0])
        && info[1]->IsNumber())
      {
        try
        {
          ::Windows::System::Threading::TimerElapsedHandler^ arg0 = dynamic_cast<::Windows::System::Threading::TimerElapsedHandler^>(NodeRT::Utils::GetObjectInstance(info[0]));
          ::Windows::Foundation::TimeSpan arg1 = NodeRT::Utils::TimeSpanFromMilli(Nan::To<int64_t>(info[1]).FromMaybe(0));
          
          ::Windows::System::Threading::ThreadPoolTimer^ result;
          result = ::Windows::System::Threading::ThreadPoolTimer::CreateTimer(arg0, arg1);
          info.GetReturnValue().Set(WrapThreadPoolTimer(result));
          return;
        }
        catch (Platform::Exception ^exception)
        {
          NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
          return;
        }
      }
      else if (info.Length() == 3
        && NodeRT::Utils::IsWinRtWrapperOf<::Windows::System::Threading::TimerElapsedHandler^>(info[0])
        && info[1]->IsNumber()
        && NodeRT::Utils::IsWinRtWrapperOf<::Windows::System::Threading::TimerDestroyedHandler^>(info[2]))
      {
        try
        {
          ::Windows::System::Threading::TimerElapsedHandler^ arg0 = dynamic_cast<::Windows::System::Threading::TimerElapsedHandler^>(NodeRT::Utils::GetObjectInstance(info[0]));
          ::Windows::Foundation::TimeSpan arg1 = NodeRT::Utils::TimeSpanFromMilli(Nan::To<int64_t>(info[1]).FromMaybe(0));
          ::Windows::System::Threading::TimerDestroyedHandler^ arg2 = dynamic_cast<::Windows::System::Threading::TimerDestroyedHandler^>(NodeRT::Utils::GetObjectInstance(info[2]));
          
          ::Windows::System::Threading::ThreadPoolTimer^ result;
          result = ::Windows::System::Threading::ThreadPoolTimer::CreateTimer(arg0, arg1, arg2);
          info.GetReturnValue().Set(WrapThreadPoolTimer(result));
          return;
        }
        catch (Platform::Exception ^exception)
        {
          NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
          return;
        }
      }
 else  {
        Nan::ThrowError(Nan::Error(NodeRT::Utils::NewString(L"Bad arguments: no suitable overload found")));
        return;
      }
    }

    static void DelayGetter(Local<String> property, const Nan::PropertyCallbackInfo<v8::Value> &info) {
      HandleScope scope;

      if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::System::Threading::ThreadPoolTimer^>(info.This())) {
        return;
      }

      ThreadPoolTimer *wrapper = ThreadPoolTimer::Unwrap<ThreadPoolTimer>(info.This());

      try  {
        ::Windows::Foundation::TimeSpan result = wrapper->_instance->Delay;
        info.GetReturnValue().Set(Nan::New<Number>(result.Duration/10000.0));
        return;
      } catch (Platform::Exception ^exception) {
        NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
        return;
      }
    }
      
    static void PeriodGetter(Local<String> property, const Nan::PropertyCallbackInfo<v8::Value> &info) {
      HandleScope scope;

      if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::System::Threading::ThreadPoolTimer^>(info.This())) {
        return;
      }

      ThreadPoolTimer *wrapper = ThreadPoolTimer::Unwrap<ThreadPoolTimer>(info.This());

      try  {
        ::Windows::Foundation::TimeSpan result = wrapper->_instance->Period;
        info.GetReturnValue().Set(Nan::New<Number>(result.Duration/10000.0));
        return;
      } catch (Platform::Exception ^exception) {
        NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
        return;
      }
    }
      


    private:
      ::Windows::System::Threading::ThreadPoolTimer^ _instance;
      static Persistent<FunctionTemplate> s_constructorTemplate;

      friend v8::Local<v8::Value> WrapThreadPoolTimer(::Windows::System::Threading::ThreadPoolTimer^ wintRtInstance);
      friend ::Windows::System::Threading::ThreadPoolTimer^ UnwrapThreadPoolTimer(Local<Value> value);
  };

  Persistent<FunctionTemplate> ThreadPoolTimer::s_constructorTemplate;

  v8::Local<v8::Value> WrapThreadPoolTimer(::Windows::System::Threading::ThreadPoolTimer^ 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>(ThreadPoolTimer::s_constructorTemplate);
    return scope.Escape(Nan::NewInstance(Nan::GetFunction(localRef).ToLocalChecked(),_countof(args), args).ToLocalChecked());
  }

  ::Windows::System::Threading::ThreadPoolTimer^ UnwrapThreadPoolTimer(Local<Value> value) {
     return ThreadPoolTimer::Unwrap<ThreadPoolTimer>(Nan::To<Object>(value).ToLocalChecked())->_instance;
  }

  void InitThreadPoolTimer(Local<Object> exports) {
    ThreadPoolTimer::Init(exports);
  }

  class ThreadPool : 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>("ThreadPool").ToLocalChecked());
        localRef->InstanceTemplate()->SetInternalFieldCount(1);

        Local<Function> func;
        Local<FunctionTemplate> funcTemplate;





        Local<Object> constructor = Nan::To<Object>(Nan::GetFunction(localRef).ToLocalChecked()).ToLocalChecked();
        Nan::SetMethod(constructor, "castFrom", CastFrom);

        func = Nan::GetFunction(Nan::New<FunctionTemplate>(RunAsync)).ToLocalChecked();
        Nan::Set(constructor, Nan::New<String>("runAsync").ToLocalChecked(), func);


        Nan::Set(exports, Nan::New<String>("ThreadPool").ToLocalChecked(), constructor);
      }

      virtual ::Platform::Object^ GetObjectInstance() const override {
        return _instance;
      }

    private:

      ThreadPool(::Windows::System::Threading::ThreadPool^ 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::System::Threading::ThreadPool^ winRtInstance;


      if (info.Length() == 1 && OpaqueWrapper::IsOpaqueWrapper(info[0]) &&
        NodeRT::Utils::IsWinRtWrapperOf<::Windows::System::Threading::ThreadPool^>(info[0])) {
        try {
          winRtInstance = (::Windows::System::Threading::ThreadPool^) 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());

      ThreadPool *wrapperInstance = new ThreadPool(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::System::Threading::ThreadPool^>(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::System::Threading::ThreadPool^ winRtInstance;
      try {
        winRtInstance = (::Windows::System::Threading::ThreadPool^) NodeRT::Utils::GetObjectInstance(info[0]);
      } catch (Platform::Exception ^exception) {
        NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
        return;
      }

      info.GetReturnValue().Set(WrapThreadPool(winRtInstance));
    }




    static void RunAsync(Nan::NAN_METHOD_ARGS_TYPE info) {
      HandleScope scope;

      if (info.Length() == 0 || !info[info.Length() -1]->IsFunction()) {
        Nan::ThrowError(Nan::Error(NodeRT::Utils::NewString(L"Bad arguments: No callback was given")));
        return;
      }

      ::Windows::Foundation::IAsyncAction^ op;


      if (info.Length() == 2
          && NodeRT::Utils::IsWinRtWrapperOf<::Windows::System::Threading::WorkItemHandler^>(info[0]))
      {
        try
        {
          ::Windows::System::Threading::WorkItemHandler^ arg0 = dynamic_cast<::Windows::System::Threading::WorkItemHandler^>(NodeRT::Utils::GetObjectInstance(info[0]));
            
          op = ::Windows::System::Threading::ThreadPool::RunAsync(arg0);
        } catch (Platform::Exception ^exception) {
            NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
            return;
        }
      }
      else if (info.Length() == 3
          && NodeRT::Utils::IsWinRtWrapperOf<::Windows::System::Threading::WorkItemHandler^>(info[0])
          && info[1]->IsInt32())
      {
        try
        {
          ::Windows::System::Threading::WorkItemHandler^ arg0 = dynamic_cast<::Windows::System::Threading::WorkItemHandler^>(NodeRT::Utils::GetObjectInstance(info[0]));
          ::Windows::System::Threading::WorkItemPriority arg1 = static_cast<::Windows::System::Threading::WorkItemPriority>(Nan::To<int32_t>(info[1]).FromMaybe(0));
            
          op = ::Windows::System::Threading::ThreadPool::RunAsync(arg0,arg1);
        } catch (Platform::Exception ^exception) {
            NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
            return;
        }
      }
      else if (info.Length() == 4
          && NodeRT::Utils::IsWinRtWrapperOf<::Windows::System::Threading::WorkItemHandler^>(info[0])
          && info[1]->IsInt32()
          && info[2]->IsInt32())
      {
        try
        {
          ::Windows::System::Threading::WorkItemHandler^ arg0 = dynamic_cast<::Windows::System::Threading::WorkItemHandler^>(NodeRT::Utils::GetObjectInstance(info[0]));
          ::Windows::System::Threading::WorkItemPriority arg1 = static_cast<::Windows::System::Threading::WorkItemPriority>(Nan::To<int32_t>(info[1]).FromMaybe(0));
          ::Windows::System::Threading::WorkItemOptions arg2 = static_cast<::Windows::System::Threading::WorkItemOptions>(Nan::To<int32_t>(info[2]).FromMaybe(0));
            
          op = ::Windows::System::Threading::ThreadPool::RunAsync(arg0,arg1,arg2);
        } catch (Platform::Exception ^exception) {
            NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
            return;
        }
      }
 else {
        Nan::ThrowError(Nan::Error(NodeRT::Utils::NewString(L"Bad arguments: no suitable overload found")));
        return;
      }

      auto opTask = create_task(op);
      uv_async_t* asyncToken = NodeUtils::Async::GetAsyncToken(info[info.Length() -1].As<Function>());

      opTask.then( [asyncToken] (task<void> t)
      {
        try {
          t.get();
          NodeUtils::Async::RunCallbackOnMain(asyncToken, [](NodeUtils::InvokeCallbackDelegate invokeCallback) {


                Local<Value> args[] = {Undefined()};


            invokeCallback(_countof(args), args);
          });
        }
        catch (Platform::Exception^ exception)
        {
          NodeUtils::Async::RunCallbackOnMain(asyncToken, [exception](NodeUtils::InvokeCallbackDelegate invokeCallback) {

            Local<Value> error = NodeRT::Utils::WinRtExceptionToJsError(exception);

            Local<Value> args[] = {error};
            invokeCallback(_countof(args), args);
          });
        }
      });
    }




    private:
      ::Windows::System::Threading::ThreadPool^ _instance;
      static Persistent<FunctionTemplate> s_constructorTemplate;

      friend v8::Local<v8::Value> WrapThreadPool(::Windows::System::Threading::ThreadPool^ wintRtInstance);
      friend ::Windows::System::Threading::ThreadPool^ UnwrapThreadPool(Local<Value> value);
  };

  Persistent<FunctionTemplate> ThreadPool::s_constructorTemplate;

  v8::Local<v8::Value> WrapThreadPool(::Windows::System::Threading::ThreadPool^ 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>(ThreadPool::s_constructorTemplate);
    return scope.Escape(Nan::NewInstance(Nan::GetFunction(localRef).ToLocalChecked(),_countof(args), args).ToLocalChecked());
  }

  ::Windows::System::Threading::ThreadPool^ UnwrapThreadPool(Local<Value> value) {
     return ThreadPool::Unwrap<ThreadPool>(Nan::To<Object>(value).ToLocalChecked())->_instance;
  }

  void InitThreadPool(Local<Object> exports) {
    ThreadPool::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::System::Threading::InitWorkItemPriorityEnum(target);
      NodeRT::Windows::System::Threading::InitWorkItemOptionsEnum(target);
      NodeRT::Windows::System::Threading::InitThreadPoolTimer(target);
      NodeRT::Windows::System::Threading::InitThreadPool(target);


  NodeRT::Utils::RegisterNameSpace("Windows.System.Threading", target);
}



NODE_MODULE(binding, init)
