// 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.

// 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::Handle;
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 Devices { namespace Geolocation { namespace Geofencing { 

  v8::Local<v8::Value> WrapGeofence(::Windows::Devices::Geolocation::Geofencing::Geofence^ wintRtInstance);
  ::Windows::Devices::Geolocation::Geofencing::Geofence^ UnwrapGeofence(Local<Value> value);
  
  v8::Local<v8::Value> WrapGeofenceMonitor(::Windows::Devices::Geolocation::Geofencing::GeofenceMonitor^ wintRtInstance);
  ::Windows::Devices::Geolocation::Geofencing::GeofenceMonitor^ UnwrapGeofenceMonitor(Local<Value> value);
  
  v8::Local<v8::Value> WrapGeofenceStateChangeReport(::Windows::Devices::Geolocation::Geofencing::GeofenceStateChangeReport^ wintRtInstance);
  ::Windows::Devices::Geolocation::Geofencing::GeofenceStateChangeReport^ UnwrapGeofenceStateChangeReport(Local<Value> value);
  


  static void InitMonitoredGeofenceStatesEnum(const Local<Object> exports)
  {
    HandleScope scope;
    
	Local<Object> enumObject = Nan::New<Object>();
    Nan::Set(exports, Nan::New<String>("MonitoredGeofenceStates").ToLocalChecked(), enumObject);
	Nan::Set(enumObject, Nan::New<String>("none").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::Devices::Geolocation::Geofencing::MonitoredGeofenceStates::None)));
	Nan::Set(enumObject, Nan::New<String>("entered").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::Devices::Geolocation::Geofencing::MonitoredGeofenceStates::Entered)));
	Nan::Set(enumObject, Nan::New<String>("exited").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::Devices::Geolocation::Geofencing::MonitoredGeofenceStates::Exited)));
	Nan::Set(enumObject, Nan::New<String>("removed").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::Devices::Geolocation::Geofencing::MonitoredGeofenceStates::Removed)));
  }


  static void InitGeofenceStateEnum(const Local<Object> exports)
  {
    HandleScope scope;
    
	Local<Object> enumObject = Nan::New<Object>();
    Nan::Set(exports, Nan::New<String>("GeofenceState").ToLocalChecked(), enumObject);
	Nan::Set(enumObject, Nan::New<String>("none").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::Devices::Geolocation::Geofencing::GeofenceState::None)));
	Nan::Set(enumObject, Nan::New<String>("entered").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::Devices::Geolocation::Geofencing::GeofenceState::Entered)));
	Nan::Set(enumObject, Nan::New<String>("exited").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::Devices::Geolocation::Geofencing::GeofenceState::Exited)));
	Nan::Set(enumObject, Nan::New<String>("removed").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::Devices::Geolocation::Geofencing::GeofenceState::Removed)));
  }


  static void InitGeofenceMonitorStatusEnum(const Local<Object> exports)
  {
    HandleScope scope;
    
	Local<Object> enumObject = Nan::New<Object>();
    Nan::Set(exports, Nan::New<String>("GeofenceMonitorStatus").ToLocalChecked(), enumObject);
	Nan::Set(enumObject, Nan::New<String>("ready").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::Devices::Geolocation::Geofencing::GeofenceMonitorStatus::Ready)));
	Nan::Set(enumObject, Nan::New<String>("initializing").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::Devices::Geolocation::Geofencing::GeofenceMonitorStatus::Initializing)));
	Nan::Set(enumObject, Nan::New<String>("noData").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::Devices::Geolocation::Geofencing::GeofenceMonitorStatus::NoData)));
	Nan::Set(enumObject, Nan::New<String>("disabled").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::Devices::Geolocation::Geofencing::GeofenceMonitorStatus::Disabled)));
	Nan::Set(enumObject, Nan::New<String>("notInitialized").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::Devices::Geolocation::Geofencing::GeofenceMonitorStatus::NotInitialized)));
	Nan::Set(enumObject, Nan::New<String>("notAvailable").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::Devices::Geolocation::Geofencing::GeofenceMonitorStatus::NotAvailable)));
  }


  static void InitGeofenceRemovalReasonEnum(const Local<Object> exports)
  {
    HandleScope scope;
    
	Local<Object> enumObject = Nan::New<Object>();
    Nan::Set(exports, Nan::New<String>("GeofenceRemovalReason").ToLocalChecked(), enumObject);
	Nan::Set(enumObject, Nan::New<String>("used").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::Devices::Geolocation::Geofencing::GeofenceRemovalReason::Used)));
	Nan::Set(enumObject, Nan::New<String>("expired").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::Devices::Geolocation::Geofencing::GeofenceRemovalReason::Expired)));
  }



  
  class Geofence : 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>("Geofence").ToLocalChecked());
      localRef->InstanceTemplate()->SetInternalFieldCount(1);
      
                              
      Nan::SetAccessor(localRef->PrototypeTemplate(), Nan::New<String>("duration").ToLocalChecked(), DurationGetter);
      Nan::SetAccessor(localRef->PrototypeTemplate(), Nan::New<String>("dwellTime").ToLocalChecked(), DwellTimeGetter);
      Nan::SetAccessor(localRef->PrototypeTemplate(), Nan::New<String>("geoshape").ToLocalChecked(), GeoshapeGetter);
      Nan::SetAccessor(localRef->PrototypeTemplate(), Nan::New<String>("id").ToLocalChecked(), IdGetter);
      Nan::SetAccessor(localRef->PrototypeTemplate(), Nan::New<String>("monitoredStates").ToLocalChecked(), MonitoredStatesGetter);
      Nan::SetAccessor(localRef->PrototypeTemplate(), Nan::New<String>("singleUse").ToLocalChecked(), SingleUseGetter);
      Nan::SetAccessor(localRef->PrototypeTemplate(), Nan::New<String>("startTime").ToLocalChecked(), StartTimeGetter);
      
      Local<Object> constructor = Nan::To<Object>(Nan::GetFunction(localRef).ToLocalChecked()).ToLocalChecked();
	  Nan::SetMethod(constructor, "castFrom", CastFrom);


      Nan::Set(exports, Nan::New<String>("Geofence").ToLocalChecked(), constructor);
    }


    virtual ::Platform::Object^ GetObjectInstance() const override
    {
      return _instance;
    }

  private:
    
    Geofence(::Windows::Devices::Geolocation::Geofencing::Geofence^ 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::Devices::Geolocation::Geofencing::Geofence^ winRtInstance;


      if (info.Length() == 1 && OpaqueWrapper::IsOpaqueWrapper(info[0]) &&
        NodeRT::Utils::IsWinRtWrapperOf<::Windows::Devices::Geolocation::Geofencing::Geofence^>(info[0]))
      {
        try 
        {
          winRtInstance = (::Windows::Devices::Geolocation::Geofencing::Geofence^) NodeRT::Utils::GetObjectInstance(info[0]);
        }
        catch (Platform::Exception ^exception)
        {
          NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
          return;
        }
      }
      else if (info.Length() == 2
        && info[0]->IsString()
        && NodeRT::Utils::IsWinRtWrapperOf<::Windows::Devices::Geolocation::IGeoshape^>(info[1]))
      {
        try
        {
          Platform::String^ arg0 = ref new Platform::String(NodeRT::Utils::StringToWchar(v8::String::Value(info[0])));
          ::Windows::Devices::Geolocation::IGeoshape^ arg1 = dynamic_cast<::Windows::Devices::Geolocation::IGeoshape^>(NodeRT::Utils::GetObjectInstance(info[1]));
          
          winRtInstance = ref new ::Windows::Devices::Geolocation::Geofencing::Geofence(arg0,arg1);
        }
        catch (Platform::Exception ^exception)
        {
          NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
          return;
        }
      }
      else if (info.Length() == 4
        && info[0]->IsString()
        && NodeRT::Utils::IsWinRtWrapperOf<::Windows::Devices::Geolocation::IGeoshape^>(info[1])
        && info[2]->IsInt32()
        && info[3]->IsBoolean())
      {
        try
        {
          Platform::String^ arg0 = ref new Platform::String(NodeRT::Utils::StringToWchar(v8::String::Value(info[0])));
          ::Windows::Devices::Geolocation::IGeoshape^ arg1 = dynamic_cast<::Windows::Devices::Geolocation::IGeoshape^>(NodeRT::Utils::GetObjectInstance(info[1]));
          ::Windows::Devices::Geolocation::Geofencing::MonitoredGeofenceStates arg2 = static_cast<::Windows::Devices::Geolocation::Geofencing::MonitoredGeofenceStates>(Nan::To<int32_t>(info[2]).FromMaybe(0));
          bool arg3 = Nan::To<bool>(info[3]).FromMaybe(false);
          
          winRtInstance = ref new ::Windows::Devices::Geolocation::Geofencing::Geofence(arg0,arg1,arg2,arg3);
        }
        catch (Platform::Exception ^exception)
        {
          NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
          return;
        }
      }
      else if (info.Length() == 5
        && info[0]->IsString()
        && NodeRT::Utils::IsWinRtWrapperOf<::Windows::Devices::Geolocation::IGeoshape^>(info[1])
        && info[2]->IsInt32()
        && info[3]->IsBoolean()
        && info[4]->IsNumber())
      {
        try
        {
          Platform::String^ arg0 = ref new Platform::String(NodeRT::Utils::StringToWchar(v8::String::Value(info[0])));
          ::Windows::Devices::Geolocation::IGeoshape^ arg1 = dynamic_cast<::Windows::Devices::Geolocation::IGeoshape^>(NodeRT::Utils::GetObjectInstance(info[1]));
          ::Windows::Devices::Geolocation::Geofencing::MonitoredGeofenceStates arg2 = static_cast<::Windows::Devices::Geolocation::Geofencing::MonitoredGeofenceStates>(Nan::To<int32_t>(info[2]).FromMaybe(0));
          bool arg3 = Nan::To<bool>(info[3]).FromMaybe(false);
          ::Windows::Foundation::TimeSpan arg4 = NodeRT::Utils::TimeSpanFromMilli(Nan::To<int64_t>(info[4]).FromMaybe(0));
          
          winRtInstance = ref new ::Windows::Devices::Geolocation::Geofencing::Geofence(arg0,arg1,arg2,arg3,arg4);
        }
        catch (Platform::Exception ^exception)
        {
          NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
          return;
        }
      }
      else if (info.Length() == 7
        && info[0]->IsString()
        && NodeRT::Utils::IsWinRtWrapperOf<::Windows::Devices::Geolocation::IGeoshape^>(info[1])
        && info[2]->IsInt32()
        && info[3]->IsBoolean()
        && info[4]->IsNumber()
        && info[5]->IsDate()
        && info[6]->IsNumber())
      {
        try
        {
          Platform::String^ arg0 = ref new Platform::String(NodeRT::Utils::StringToWchar(v8::String::Value(info[0])));
          ::Windows::Devices::Geolocation::IGeoshape^ arg1 = dynamic_cast<::Windows::Devices::Geolocation::IGeoshape^>(NodeRT::Utils::GetObjectInstance(info[1]));
          ::Windows::Devices::Geolocation::Geofencing::MonitoredGeofenceStates arg2 = static_cast<::Windows::Devices::Geolocation::Geofencing::MonitoredGeofenceStates>(Nan::To<int32_t>(info[2]).FromMaybe(0));
          bool arg3 = Nan::To<bool>(info[3]).FromMaybe(false);
          ::Windows::Foundation::TimeSpan arg4 = NodeRT::Utils::TimeSpanFromMilli(Nan::To<int64_t>(info[4]).FromMaybe(0));
          ::Windows::Foundation::DateTime arg5 = NodeRT::Utils::DateTimeFromJSDate(info[5]);
          ::Windows::Foundation::TimeSpan arg6 = NodeRT::Utils::TimeSpanFromMilli(Nan::To<int64_t>(info[6]).FromMaybe(0));
          
          winRtInstance = ref new ::Windows::Devices::Geolocation::Geofencing::Geofence(arg0,arg1,arg2,arg3,arg4,arg5,arg6);
        }
        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());

      Geofence *wrapperInstance = new Geofence(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::Devices::Geolocation::Geofencing::Geofence^>(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::Devices::Geolocation::Geofencing::Geofence^ winRtInstance;
		try
		{
			winRtInstance = (::Windows::Devices::Geolocation::Geofencing::Geofence^) NodeRT::Utils::GetObjectInstance(info[0]);
		}
		catch (Platform::Exception ^exception)
		{
			NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
			return;
		}

		info.GetReturnValue().Set(WrapGeofence(winRtInstance));
    }


  



    static void DurationGetter(Local<String> property, const Nan::PropertyCallbackInfo<v8::Value> &info)
    {
      HandleScope scope;
      
      if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::Devices::Geolocation::Geofencing::Geofence^>(info.This()))
      {
        return;
      }

      Geofence *wrapper = Geofence::Unwrap<Geofence>(info.This());

      try 
      {
        ::Windows::Foundation::TimeSpan result = wrapper->_instance->Duration;
        info.GetReturnValue().Set(Nan::New<Number>(result.Duration/10000.0));
        return;
      }
      catch (Platform::Exception ^exception)
      {
        NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
        return;
      }
    }
    
    static void DwellTimeGetter(Local<String> property, const Nan::PropertyCallbackInfo<v8::Value> &info)
    {
      HandleScope scope;
      
      if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::Devices::Geolocation::Geofencing::Geofence^>(info.This()))
      {
        return;
      }

      Geofence *wrapper = Geofence::Unwrap<Geofence>(info.This());

      try 
      {
        ::Windows::Foundation::TimeSpan result = wrapper->_instance->DwellTime;
        info.GetReturnValue().Set(Nan::New<Number>(result.Duration/10000.0));
        return;
      }
      catch (Platform::Exception ^exception)
      {
        NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
        return;
      }
    }
    
    static void GeoshapeGetter(Local<String> property, const Nan::PropertyCallbackInfo<v8::Value> &info)
    {
      HandleScope scope;
      
      if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::Devices::Geolocation::Geofencing::Geofence^>(info.This()))
      {
        return;
      }

      Geofence *wrapper = Geofence::Unwrap<Geofence>(info.This());

      try 
      {
        ::Windows::Devices::Geolocation::IGeoshape^ result = wrapper->_instance->Geoshape;
        info.GetReturnValue().Set(NodeRT::Utils::CreateExternalWinRTObject("Windows.Devices.Geolocation", "IGeoshape", result));
        return;
      }
      catch (Platform::Exception ^exception)
      {
        NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
        return;
      }
    }
    
    static void IdGetter(Local<String> property, const Nan::PropertyCallbackInfo<v8::Value> &info)
    {
      HandleScope scope;
      
      if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::Devices::Geolocation::Geofencing::Geofence^>(info.This()))
      {
        return;
      }

      Geofence *wrapper = Geofence::Unwrap<Geofence>(info.This());

      try 
      {
        Platform::String^ result = wrapper->_instance->Id;
        info.GetReturnValue().Set(NodeRT::Utils::NewString(result->Data()));
        return;
      }
      catch (Platform::Exception ^exception)
      {
        NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
        return;
      }
    }
    
    static void MonitoredStatesGetter(Local<String> property, const Nan::PropertyCallbackInfo<v8::Value> &info)
    {
      HandleScope scope;
      
      if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::Devices::Geolocation::Geofencing::Geofence^>(info.This()))
      {
        return;
      }

      Geofence *wrapper = Geofence::Unwrap<Geofence>(info.This());

      try 
      {
        ::Windows::Devices::Geolocation::Geofencing::MonitoredGeofenceStates result = wrapper->_instance->MonitoredStates;
        info.GetReturnValue().Set(Nan::New<Integer>(static_cast<int>(result)));
        return;
      }
      catch (Platform::Exception ^exception)
      {
        NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
        return;
      }
    }
    
    static void SingleUseGetter(Local<String> property, const Nan::PropertyCallbackInfo<v8::Value> &info)
    {
      HandleScope scope;
      
      if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::Devices::Geolocation::Geofencing::Geofence^>(info.This()))
      {
        return;
      }

      Geofence *wrapper = Geofence::Unwrap<Geofence>(info.This());

      try 
      {
        bool result = wrapper->_instance->SingleUse;
        info.GetReturnValue().Set(Nan::New<Boolean>(result));
        return;
      }
      catch (Platform::Exception ^exception)
      {
        NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
        return;
      }
    }
    
    static void StartTimeGetter(Local<String> property, const Nan::PropertyCallbackInfo<v8::Value> &info)
    {
      HandleScope scope;
      
      if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::Devices::Geolocation::Geofencing::Geofence^>(info.This()))
      {
        return;
      }

      Geofence *wrapper = Geofence::Unwrap<Geofence>(info.This());

      try 
      {
        ::Windows::Foundation::DateTime result = wrapper->_instance->StartTime;
        info.GetReturnValue().Set(NodeRT::Utils::DateTimeToJS(result));
        return;
      }
      catch (Platform::Exception ^exception)
      {
        NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
        return;
      }
    }
    


  private:
    ::Windows::Devices::Geolocation::Geofencing::Geofence^ _instance;
    static Persistent<FunctionTemplate> s_constructorTemplate;

    friend v8::Local<v8::Value> WrapGeofence(::Windows::Devices::Geolocation::Geofencing::Geofence^ wintRtInstance);
    friend ::Windows::Devices::Geolocation::Geofencing::Geofence^ UnwrapGeofence(Local<Value> value);
  };
  Persistent<FunctionTemplate> Geofence::s_constructorTemplate;

  v8::Local<v8::Value> WrapGeofence(::Windows::Devices::Geolocation::Geofencing::Geofence^ 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>(Geofence::s_constructorTemplate);
    return scope.Escape(Nan::NewInstance(Nan::GetFunction(localRef).ToLocalChecked(),_countof(args), args).ToLocalChecked());
  }

  ::Windows::Devices::Geolocation::Geofencing::Geofence^ UnwrapGeofence(Local<Value> value)
  {
     return Geofence::Unwrap<Geofence>(Nan::To<Object>(value).ToLocalChecked())->_instance;
  }

  void InitGeofence(Local<Object> exports)
  {
    Geofence::Init(exports);
  }

  class GeofenceMonitor : 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>("GeofenceMonitor").ToLocalChecked());
      localRef->InstanceTemplate()->SetInternalFieldCount(1);
      
            
      Nan::SetPrototypeMethod(localRef, "readReports", ReadReports);
      
                  
      Nan::SetPrototypeMethod(localRef,"addListener", AddListener);
      Nan::SetPrototypeMethod(localRef,"on", AddListener);
      Nan::SetPrototypeMethod(localRef,"removeListener", RemoveListener);
      Nan::SetPrototypeMethod(localRef, "off", RemoveListener);
            
      Nan::SetAccessor(localRef->PrototypeTemplate(), Nan::New<String>("geofences").ToLocalChecked(), GeofencesGetter);
      Nan::SetAccessor(localRef->PrototypeTemplate(), Nan::New<String>("lastKnownGeoposition").ToLocalChecked(), LastKnownGeopositionGetter);
      Nan::SetAccessor(localRef->PrototypeTemplate(), Nan::New<String>("status").ToLocalChecked(), StatusGetter);
      
      Local<Object> constructor = Nan::To<Object>(Nan::GetFunction(localRef).ToLocalChecked()).ToLocalChecked();
	  Nan::SetMethod(constructor, "castFrom", CastFrom);

      Nan::SetAccessor(constructor, Nan::New<String>("current").ToLocalChecked(), CurrentGetter);

      Nan::Set(exports, Nan::New<String>("GeofenceMonitor").ToLocalChecked(), constructor);
    }


    virtual ::Platform::Object^ GetObjectInstance() const override
    {
      return _instance;
    }

  private:
    
    GeofenceMonitor(::Windows::Devices::Geolocation::Geofencing::GeofenceMonitor^ 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::Devices::Geolocation::Geofencing::GeofenceMonitor^ winRtInstance;


      if (info.Length() == 1 && OpaqueWrapper::IsOpaqueWrapper(info[0]) &&
        NodeRT::Utils::IsWinRtWrapperOf<::Windows::Devices::Geolocation::Geofencing::GeofenceMonitor^>(info[0]))
      {
        try 
        {
          winRtInstance = (::Windows::Devices::Geolocation::Geofencing::GeofenceMonitor^) 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());

      GeofenceMonitor *wrapperInstance = new GeofenceMonitor(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::Devices::Geolocation::Geofencing::GeofenceMonitor^>(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::Devices::Geolocation::Geofencing::GeofenceMonitor^ winRtInstance;
		try
		{
			winRtInstance = (::Windows::Devices::Geolocation::Geofencing::GeofenceMonitor^) NodeRT::Utils::GetObjectInstance(info[0]);
		}
		catch (Platform::Exception ^exception)
		{
			NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
			return;
		}

		info.GetReturnValue().Set(WrapGeofenceMonitor(winRtInstance));
    }


  
    static void ReadReports(Nan::NAN_METHOD_ARGS_TYPE info)
    {
      HandleScope scope;

      if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::Devices::Geolocation::Geofencing::GeofenceMonitor^>(info.This()))
      {
        return;
      }

      GeofenceMonitor *wrapper = GeofenceMonitor::Unwrap<GeofenceMonitor>(info.This());

      if (info.Length() == 0)
      {
        try
        {
          ::Windows::Foundation::Collections::IVectorView<::Windows::Devices::Geolocation::Geofencing::GeofenceStateChangeReport^>^ result;
          result = wrapper->_instance->ReadReports();
          info.GetReturnValue().Set(NodeRT::Collections::VectorViewWrapper<::Windows::Devices::Geolocation::Geofencing::GeofenceStateChangeReport^>::CreateVectorViewWrapper(result, 
            [](::Windows::Devices::Geolocation::Geofencing::GeofenceStateChangeReport^ val) -> Local<Value> {
              return WrapGeofenceStateChangeReport(val);
            },
            [](Local<Value> value) -> bool {
              return NodeRT::Utils::IsWinRtWrapperOf<::Windows::Devices::Geolocation::Geofencing::GeofenceStateChangeReport^>(value);
            },
            [](Local<Value> value) -> ::Windows::Devices::Geolocation::Geofencing::GeofenceStateChangeReport^ {
              return UnwrapGeofenceStateChangeReport(value);
            }
          ));
          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 GeofencesGetter(Local<String> property, const Nan::PropertyCallbackInfo<v8::Value> &info)
    {
      HandleScope scope;
      
      if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::Devices::Geolocation::Geofencing::GeofenceMonitor^>(info.This()))
      {
        return;
      }

      GeofenceMonitor *wrapper = GeofenceMonitor::Unwrap<GeofenceMonitor>(info.This());

      try 
      {
        ::Windows::Foundation::Collections::IVector<::Windows::Devices::Geolocation::Geofencing::Geofence^>^ result = wrapper->_instance->Geofences;
        info.GetReturnValue().Set(NodeRT::Collections::VectorWrapper<::Windows::Devices::Geolocation::Geofencing::Geofence^>::CreateVectorWrapper(result, 
            [](::Windows::Devices::Geolocation::Geofencing::Geofence^ val) -> Local<Value> {
              return WrapGeofence(val);
            },
            [](Local<Value> value) -> bool {
              return NodeRT::Utils::IsWinRtWrapperOf<::Windows::Devices::Geolocation::Geofencing::Geofence^>(value);
            },
            [](Local<Value> value) -> ::Windows::Devices::Geolocation::Geofencing::Geofence^ {
              return UnwrapGeofence(value);
            }
          ));
        return;
      }
      catch (Platform::Exception ^exception)
      {
        NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
        return;
      }
    }
    
    static void LastKnownGeopositionGetter(Local<String> property, const Nan::PropertyCallbackInfo<v8::Value> &info)
    {
      HandleScope scope;
      
      if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::Devices::Geolocation::Geofencing::GeofenceMonitor^>(info.This()))
      {
        return;
      }

      GeofenceMonitor *wrapper = GeofenceMonitor::Unwrap<GeofenceMonitor>(info.This());

      try 
      {
        ::Windows::Devices::Geolocation::Geoposition^ result = wrapper->_instance->LastKnownGeoposition;
        info.GetReturnValue().Set(NodeRT::Utils::CreateExternalWinRTObject("Windows.Devices.Geolocation", "Geoposition", result));
        return;
      }
      catch (Platform::Exception ^exception)
      {
        NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
        return;
      }
    }
    
    static void StatusGetter(Local<String> property, const Nan::PropertyCallbackInfo<v8::Value> &info)
    {
      HandleScope scope;
      
      if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::Devices::Geolocation::Geofencing::GeofenceMonitor^>(info.This()))
      {
        return;
      }

      GeofenceMonitor *wrapper = GeofenceMonitor::Unwrap<GeofenceMonitor>(info.This());

      try 
      {
        ::Windows::Devices::Geolocation::Geofencing::GeofenceMonitorStatus result = wrapper->_instance->Status;
        info.GetReturnValue().Set(Nan::New<Integer>(static_cast<int>(result)));
        return;
      }
      catch (Platform::Exception ^exception)
      {
        NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
        return;
      }
    }
    

    static void CurrentGetter(Local<String> property, const Nan::PropertyCallbackInfo<v8::Value> &info)
    {
      HandleScope scope;

      try 
      {
        ::Windows::Devices::Geolocation::Geofencing::GeofenceMonitor^ result = ::Windows::Devices::Geolocation::Geofencing::GeofenceMonitor::Current;
        info.GetReturnValue().Set(WrapGeofenceMonitor(result));
        return;
      }
      catch (Platform::Exception ^exception)
      {
        NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
        return;
      }
    }
    

    static void AddListener(Nan::NAN_METHOD_ARGS_TYPE info)
    {
      HandleScope scope;

      if (info.Length() < 2 || !info[0]->IsString() || !info[1]->IsFunction())
      {
        Nan::ThrowError(Nan::Error(NodeRT::Utils::NewString(L"wrong arguments, expected arguments are eventName(string),callback(function)")));
		return;
      }

      String::Value eventName(info[0]);
      auto str = *eventName;
      
      Local<Function> callback = info[1].As<Function>();
      
      ::Windows::Foundation::EventRegistrationToken registrationToken;
      if (NodeRT::Utils::CaseInsenstiveEquals(L"geofenceStateChanged", str))
      {
        if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::Devices::Geolocation::Geofencing::GeofenceMonitor^>(info.This()))
        {
          Nan::ThrowError(Nan::Error(NodeRT::Utils::NewString(L"The caller of this method isn't of the expected type or internal WinRt object was disposed")));
		  return;
        }
        GeofenceMonitor *wrapper = GeofenceMonitor::Unwrap<GeofenceMonitor>(info.This());
      
        try
        {
          Persistent<Object>* perstPtr = new Persistent<Object>();
          perstPtr->Reset(NodeRT::Utils::CreateCallbackObjectInDomain(callback));
          std::shared_ptr<Persistent<Object>> callbackObjPtr(perstPtr, 
            [] (Persistent<Object> *ptr ) {
              NodeUtils::Async::RunOnMain([ptr]() {
                ptr->Reset();
                delete ptr;
            });
          });

          registrationToken = wrapper->_instance->GeofenceStateChanged::add(
            ref new ::Windows::Foundation::TypedEventHandler<::Windows::Devices::Geolocation::Geofencing::GeofenceMonitor^, ::Platform::Object^>(
            [callbackObjPtr](::Windows::Devices::Geolocation::Geofencing::GeofenceMonitor^ arg0, ::Platform::Object^ arg1) {
              NodeUtils::Async::RunOnMain([callbackObjPtr , arg0, arg1]() {
           	    HandleScope scope;
                TryCatch tryCatch;
              
                Local<Value> error;

                Local<Value> wrappedArg0 = WrapGeofenceMonitor(arg0);
                Local<Value> wrappedArg1 = CreateOpaqueWrapper(arg1);

                if (tryCatch.HasCaught())
                {
                  error = Nan::To<Object>(tryCatch.Exception()).ToLocalChecked();
                }
                else 
                {
                  error = Undefined();
                }

				// TODO: this is ugly! Needed due to the possibility of expception occuring inside object convertors
				// can be fixed by wrapping the conversion code in a function and calling it on the fly
				// we must clear the try catch block here so the invoked inner method exception won't get swollen (issue #52) 
				tryCatch.~TryCatch();


                if (wrappedArg0.IsEmpty()) wrappedArg0 = Undefined();
                if (wrappedArg1.IsEmpty()) wrappedArg1 = Undefined();

                Local<Value> args[] = { wrappedArg0, wrappedArg1 };
                Local<Object> callbackObjLocalRef = Nan::New<Object>(*callbackObjPtr);
                NodeRT::Utils::CallCallbackInDomain(callbackObjLocalRef, _countof(args), args);
              });
            })
          );
        }
        catch (Platform::Exception ^exception)
        {
          NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
          return;
        }

      }
      else if (NodeRT::Utils::CaseInsenstiveEquals(L"statusChanged", str))
      {
        if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::Devices::Geolocation::Geofencing::GeofenceMonitor^>(info.This()))
        {
          Nan::ThrowError(Nan::Error(NodeRT::Utils::NewString(L"The caller of this method isn't of the expected type or internal WinRt object was disposed")));
		  return;
        }
        GeofenceMonitor *wrapper = GeofenceMonitor::Unwrap<GeofenceMonitor>(info.This());
      
        try
        {
          Persistent<Object>* perstPtr = new Persistent<Object>();
          perstPtr->Reset(NodeRT::Utils::CreateCallbackObjectInDomain(callback));
          std::shared_ptr<Persistent<Object>> callbackObjPtr(perstPtr, 
            [] (Persistent<Object> *ptr ) {
              NodeUtils::Async::RunOnMain([ptr]() {
                ptr->Reset();
                delete ptr;
            });
          });

          registrationToken = wrapper->_instance->StatusChanged::add(
            ref new ::Windows::Foundation::TypedEventHandler<::Windows::Devices::Geolocation::Geofencing::GeofenceMonitor^, ::Platform::Object^>(
            [callbackObjPtr](::Windows::Devices::Geolocation::Geofencing::GeofenceMonitor^ arg0, ::Platform::Object^ arg1) {
              NodeUtils::Async::RunOnMain([callbackObjPtr , arg0, arg1]() {
           	    HandleScope scope;
                TryCatch tryCatch;
              
                Local<Value> error;

                Local<Value> wrappedArg0 = WrapGeofenceMonitor(arg0);
                Local<Value> wrappedArg1 = CreateOpaqueWrapper(arg1);

                if (tryCatch.HasCaught())
                {
                  error = Nan::To<Object>(tryCatch.Exception()).ToLocalChecked();
                }
                else 
                {
                  error = Undefined();
                }

				// TODO: this is ugly! Needed due to the possibility of expception occuring inside object convertors
				// can be fixed by wrapping the conversion code in a function and calling it on the fly
				// we must clear the try catch block here so the invoked inner method exception won't get swollen (issue #52) 
				tryCatch.~TryCatch();


                if (wrappedArg0.IsEmpty()) wrappedArg0 = Undefined();
                if (wrappedArg1.IsEmpty()) wrappedArg1 = Undefined();

                Local<Value> args[] = { wrappedArg0, wrappedArg1 };
                Local<Object> callbackObjLocalRef = Nan::New<Object>(*callbackObjPtr);
                NodeRT::Utils::CallCallbackInDomain(callbackObjLocalRef, _countof(args), args);
              });
            })
          );
        }
        catch (Platform::Exception ^exception)
        {
          NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
          return;
        }

      }
      else 
      {
        Nan::ThrowError(Nan::Error(String::Concat(NodeRT::Utils::NewString(L"given event name isn't supported: "), info[0].As<String>())));
		return;
      }

      Local<Value> tokenMapVal = NodeRT::Utils::GetHiddenValue(callback, Nan::New<String>(REGISTRATION_TOKEN_MAP_PROPERTY_NAME).ToLocalChecked());
      Local<Object> tokenMap;

      if (tokenMapVal.IsEmpty() || Nan::Equals(tokenMapVal, Undefined()).FromMaybe(false))
      {
        tokenMap = Nan::New<Object>();
        NodeRT::Utils::SetHiddenValueWithObject(callback, Nan::New<String>(REGISTRATION_TOKEN_MAP_PROPERTY_NAME).ToLocalChecked(), tokenMap);
      }
      else
      {
        tokenMap = Nan::To<Object>(tokenMapVal).ToLocalChecked();
      }

      Nan::Set(tokenMap, info[0], CreateOpaqueWrapper(::Windows::Foundation::PropertyValue::CreateInt64(registrationToken.Value)));
    }

    static void RemoveListener(Nan::NAN_METHOD_ARGS_TYPE info)
    {
      HandleScope scope;

      if (info.Length() < 2 || !info[0]->IsString() || !info[1]->IsFunction())
      {
        Nan::ThrowError(Nan::Error(NodeRT::Utils::NewString(L"wrong arguments, expected a string and a callback")));
        return;
      }

      String::Value eventName(info[0]);
      auto str = *eventName;

      if ((NodeRT::Utils::CaseInsenstiveEquals(L"geofenceStateChanged", str)) &&(NodeRT::Utils::CaseInsenstiveEquals(L"statusChanged", str)))
      {
        Nan::ThrowError(Nan::Error(String::Concat(NodeRT::Utils::NewString(L"given event name isn't supported: "), info[0].As<String>())));
        return;
      }

      Local<Function> callback = info[1].As<Function>();
      Local<Value> tokenMap = NodeRT::Utils::GetHiddenValue(callback, Nan::New<String>(REGISTRATION_TOKEN_MAP_PROPERTY_NAME).ToLocalChecked());
                
      if (tokenMap.IsEmpty() || Nan::Equals(tokenMap, Undefined()).FromMaybe(false))
      {
        return;
      }

      Local<Value> opaqueWrapperObj =  Nan::Get(Nan::To<Object>(tokenMap).ToLocalChecked(), info[0]).ToLocalChecked();

      if (opaqueWrapperObj.IsEmpty() || Nan::Equals(opaqueWrapperObj,Undefined()).FromMaybe(false))
      {
        return;
      }

      OpaqueWrapper *opaqueWrapper = OpaqueWrapper::Unwrap<OpaqueWrapper>(opaqueWrapperObj.As<Object>());
            
      long long tokenValue = (long long) opaqueWrapper->GetObjectInstance();
      ::Windows::Foundation::EventRegistrationToken registrationToken;
      registrationToken.Value = tokenValue;
        
      try 
      {
        if (NodeRT::Utils::CaseInsenstiveEquals(L"geofenceStateChanged", str))
        {
          if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::Devices::Geolocation::Geofencing::GeofenceMonitor^>(info.This()))
          {
            Nan::ThrowError(Nan::Error(NodeRT::Utils::NewString(L"The caller of this method isn't of the expected type or internal WinRt object was disposed")));
            return;
          }
          GeofenceMonitor *wrapper = GeofenceMonitor::Unwrap<GeofenceMonitor>(info.This());
          wrapper->_instance->GeofenceStateChanged::remove(registrationToken);
        }
        else if (NodeRT::Utils::CaseInsenstiveEquals(L"statusChanged", str))
        {
          if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::Devices::Geolocation::Geofencing::GeofenceMonitor^>(info.This()))
          {
            Nan::ThrowError(Nan::Error(NodeRT::Utils::NewString(L"The caller of this method isn't of the expected type or internal WinRt object was disposed")));
            return;
          }
          GeofenceMonitor *wrapper = GeofenceMonitor::Unwrap<GeofenceMonitor>(info.This());
          wrapper->_instance->StatusChanged::remove(registrationToken);
        }
      }
      catch (Platform::Exception ^exception)
      {
        NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
      }

      Nan::Delete(Nan::To<Object>(tokenMap).ToLocalChecked(), Nan::To<String>(info[0]).ToLocalChecked());
    }
  private:
    ::Windows::Devices::Geolocation::Geofencing::GeofenceMonitor^ _instance;
    static Persistent<FunctionTemplate> s_constructorTemplate;

    friend v8::Local<v8::Value> WrapGeofenceMonitor(::Windows::Devices::Geolocation::Geofencing::GeofenceMonitor^ wintRtInstance);
    friend ::Windows::Devices::Geolocation::Geofencing::GeofenceMonitor^ UnwrapGeofenceMonitor(Local<Value> value);
  };
  Persistent<FunctionTemplate> GeofenceMonitor::s_constructorTemplate;

  v8::Local<v8::Value> WrapGeofenceMonitor(::Windows::Devices::Geolocation::Geofencing::GeofenceMonitor^ 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>(GeofenceMonitor::s_constructorTemplate);
    return scope.Escape(Nan::NewInstance(Nan::GetFunction(localRef).ToLocalChecked(),_countof(args), args).ToLocalChecked());
  }

  ::Windows::Devices::Geolocation::Geofencing::GeofenceMonitor^ UnwrapGeofenceMonitor(Local<Value> value)
  {
     return GeofenceMonitor::Unwrap<GeofenceMonitor>(Nan::To<Object>(value).ToLocalChecked())->_instance;
  }

  void InitGeofenceMonitor(Local<Object> exports)
  {
    GeofenceMonitor::Init(exports);
  }

  class GeofenceStateChangeReport : 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>("GeofenceStateChangeReport").ToLocalChecked());
      localRef->InstanceTemplate()->SetInternalFieldCount(1);
      
                              
      Nan::SetAccessor(localRef->PrototypeTemplate(), Nan::New<String>("geofence").ToLocalChecked(), GeofenceGetter);
      Nan::SetAccessor(localRef->PrototypeTemplate(), Nan::New<String>("geoposition").ToLocalChecked(), GeopositionGetter);
      Nan::SetAccessor(localRef->PrototypeTemplate(), Nan::New<String>("newState").ToLocalChecked(), NewStateGetter);
      Nan::SetAccessor(localRef->PrototypeTemplate(), Nan::New<String>("removalReason").ToLocalChecked(), RemovalReasonGetter);
      
      Local<Object> constructor = Nan::To<Object>(Nan::GetFunction(localRef).ToLocalChecked()).ToLocalChecked();
	  Nan::SetMethod(constructor, "castFrom", CastFrom);


      Nan::Set(exports, Nan::New<String>("GeofenceStateChangeReport").ToLocalChecked(), constructor);
    }


    virtual ::Platform::Object^ GetObjectInstance() const override
    {
      return _instance;
    }

  private:
    
    GeofenceStateChangeReport(::Windows::Devices::Geolocation::Geofencing::GeofenceStateChangeReport^ 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::Devices::Geolocation::Geofencing::GeofenceStateChangeReport^ winRtInstance;


      if (info.Length() == 1 && OpaqueWrapper::IsOpaqueWrapper(info[0]) &&
        NodeRT::Utils::IsWinRtWrapperOf<::Windows::Devices::Geolocation::Geofencing::GeofenceStateChangeReport^>(info[0]))
      {
        try 
        {
          winRtInstance = (::Windows::Devices::Geolocation::Geofencing::GeofenceStateChangeReport^) 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());

      GeofenceStateChangeReport *wrapperInstance = new GeofenceStateChangeReport(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::Devices::Geolocation::Geofencing::GeofenceStateChangeReport^>(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::Devices::Geolocation::Geofencing::GeofenceStateChangeReport^ winRtInstance;
		try
		{
			winRtInstance = (::Windows::Devices::Geolocation::Geofencing::GeofenceStateChangeReport^) NodeRT::Utils::GetObjectInstance(info[0]);
		}
		catch (Platform::Exception ^exception)
		{
			NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
			return;
		}

		info.GetReturnValue().Set(WrapGeofenceStateChangeReport(winRtInstance));
    }


  



    static void GeofenceGetter(Local<String> property, const Nan::PropertyCallbackInfo<v8::Value> &info)
    {
      HandleScope scope;
      
      if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::Devices::Geolocation::Geofencing::GeofenceStateChangeReport^>(info.This()))
      {
        return;
      }

      GeofenceStateChangeReport *wrapper = GeofenceStateChangeReport::Unwrap<GeofenceStateChangeReport>(info.This());

      try 
      {
        ::Windows::Devices::Geolocation::Geofencing::Geofence^ result = wrapper->_instance->Geofence;
        info.GetReturnValue().Set(WrapGeofence(result));
        return;
      }
      catch (Platform::Exception ^exception)
      {
        NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
        return;
      }
    }
    
    static void GeopositionGetter(Local<String> property, const Nan::PropertyCallbackInfo<v8::Value> &info)
    {
      HandleScope scope;
      
      if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::Devices::Geolocation::Geofencing::GeofenceStateChangeReport^>(info.This()))
      {
        return;
      }

      GeofenceStateChangeReport *wrapper = GeofenceStateChangeReport::Unwrap<GeofenceStateChangeReport>(info.This());

      try 
      {
        ::Windows::Devices::Geolocation::Geoposition^ result = wrapper->_instance->Geoposition;
        info.GetReturnValue().Set(NodeRT::Utils::CreateExternalWinRTObject("Windows.Devices.Geolocation", "Geoposition", result));
        return;
      }
      catch (Platform::Exception ^exception)
      {
        NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
        return;
      }
    }
    
    static void NewStateGetter(Local<String> property, const Nan::PropertyCallbackInfo<v8::Value> &info)
    {
      HandleScope scope;
      
      if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::Devices::Geolocation::Geofencing::GeofenceStateChangeReport^>(info.This()))
      {
        return;
      }

      GeofenceStateChangeReport *wrapper = GeofenceStateChangeReport::Unwrap<GeofenceStateChangeReport>(info.This());

      try 
      {
        ::Windows::Devices::Geolocation::Geofencing::GeofenceState result = wrapper->_instance->NewState;
        info.GetReturnValue().Set(Nan::New<Integer>(static_cast<int>(result)));
        return;
      }
      catch (Platform::Exception ^exception)
      {
        NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
        return;
      }
    }
    
    static void RemovalReasonGetter(Local<String> property, const Nan::PropertyCallbackInfo<v8::Value> &info)
    {
      HandleScope scope;
      
      if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::Devices::Geolocation::Geofencing::GeofenceStateChangeReport^>(info.This()))
      {
        return;
      }

      GeofenceStateChangeReport *wrapper = GeofenceStateChangeReport::Unwrap<GeofenceStateChangeReport>(info.This());

      try 
      {
        ::Windows::Devices::Geolocation::Geofencing::GeofenceRemovalReason result = wrapper->_instance->RemovalReason;
        info.GetReturnValue().Set(Nan::New<Integer>(static_cast<int>(result)));
        return;
      }
      catch (Platform::Exception ^exception)
      {
        NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
        return;
      }
    }
    


  private:
    ::Windows::Devices::Geolocation::Geofencing::GeofenceStateChangeReport^ _instance;
    static Persistent<FunctionTemplate> s_constructorTemplate;

    friend v8::Local<v8::Value> WrapGeofenceStateChangeReport(::Windows::Devices::Geolocation::Geofencing::GeofenceStateChangeReport^ wintRtInstance);
    friend ::Windows::Devices::Geolocation::Geofencing::GeofenceStateChangeReport^ UnwrapGeofenceStateChangeReport(Local<Value> value);
  };
  Persistent<FunctionTemplate> GeofenceStateChangeReport::s_constructorTemplate;

  v8::Local<v8::Value> WrapGeofenceStateChangeReport(::Windows::Devices::Geolocation::Geofencing::GeofenceStateChangeReport^ 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>(GeofenceStateChangeReport::s_constructorTemplate);
    return scope.Escape(Nan::NewInstance(Nan::GetFunction(localRef).ToLocalChecked(),_countof(args), args).ToLocalChecked());
  }

  ::Windows::Devices::Geolocation::Geofencing::GeofenceStateChangeReport^ UnwrapGeofenceStateChangeReport(Local<Value> value)
  {
     return GeofenceStateChangeReport::Unwrap<GeofenceStateChangeReport>(Nan::To<Object>(value).ToLocalChecked())->_instance;
  }

  void InitGeofenceStateChangeReport(Local<Object> exports)
  {
    GeofenceStateChangeReport::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::Devices::Geolocation::Geofencing::InitMonitoredGeofenceStatesEnum(target);
  NodeRT::Windows::Devices::Geolocation::Geofencing::InitGeofenceStateEnum(target);
  NodeRT::Windows::Devices::Geolocation::Geofencing::InitGeofenceMonitorStatusEnum(target);
  NodeRT::Windows::Devices::Geolocation::Geofencing::InitGeofenceRemovalReasonEnum(target);
  NodeRT::Windows::Devices::Geolocation::Geofencing::InitGeofence(target);
  NodeRT::Windows::Devices::Geolocation::Geofencing::InitGeofenceMonitor(target);
  NodeRT::Windows::Devices::Geolocation::Geofencing::InitGeofenceStateChangeReport(target);

  NodeRT::Utils::RegisterNameSpace("Windows.Devices.Geolocation.Geofencing", target);
}


NODE_MODULE(binding, init)