// 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 System { namespace Power { namespace Diagnostics { 

  v8::Local<v8::Value> WrapBackgroundEnergyDiagnostics(::Windows::System::Power::Diagnostics::BackgroundEnergyDiagnostics^ wintRtInstance);
  ::Windows::System::Power::Diagnostics::BackgroundEnergyDiagnostics^ UnwrapBackgroundEnergyDiagnostics(Local<Value> value);
  
  v8::Local<v8::Value> WrapForegroundEnergyDiagnostics(::Windows::System::Power::Diagnostics::ForegroundEnergyDiagnostics^ wintRtInstance);
  ::Windows::System::Power::Diagnostics::ForegroundEnergyDiagnostics^ UnwrapForegroundEnergyDiagnostics(Local<Value> value);
  



  
  class BackgroundEnergyDiagnostics : 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>("BackgroundEnergyDiagnostics").ToLocalChecked());
      localRef->InstanceTemplate()->SetInternalFieldCount(1);
      
                              
      Local<Object> constructor = Nan::To<Object>(Nan::GetFunction(localRef).ToLocalChecked()).ToLocalChecked();
	  Nan::SetMethod(constructor, "castFrom", CastFrom);

      Nan::SetMethod(constructor, "computeTotalEnergyUsage", ComputeTotalEnergyUsage);
      Nan::SetMethod(constructor, "resetTotalEnergyUsage", ResetTotalEnergyUsage);
      Nan::SetAccessor(constructor, Nan::New<String>("deviceSpecificConversionFactor").ToLocalChecked(), DeviceSpecificConversionFactorGetter);

      Nan::Set(exports, Nan::New<String>("BackgroundEnergyDiagnostics").ToLocalChecked(), constructor);
    }


    virtual ::Platform::Object^ GetObjectInstance() const override
    {
      return _instance;
    }

  private:
    
    BackgroundEnergyDiagnostics(::Windows::System::Power::Diagnostics::BackgroundEnergyDiagnostics^ 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::Power::Diagnostics::BackgroundEnergyDiagnostics^ winRtInstance;


      if (info.Length() == 1 && OpaqueWrapper::IsOpaqueWrapper(info[0]) &&
        NodeRT::Utils::IsWinRtWrapperOf<::Windows::System::Power::Diagnostics::BackgroundEnergyDiagnostics^>(info[0]))
      {
        try 
        {
          winRtInstance = (::Windows::System::Power::Diagnostics::BackgroundEnergyDiagnostics^) 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());

      BackgroundEnergyDiagnostics *wrapperInstance = new BackgroundEnergyDiagnostics(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::Power::Diagnostics::BackgroundEnergyDiagnostics^>(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::Power::Diagnostics::BackgroundEnergyDiagnostics^ winRtInstance;
		try
		{
			winRtInstance = (::Windows::System::Power::Diagnostics::BackgroundEnergyDiagnostics^) NodeRT::Utils::GetObjectInstance(info[0]);
		}
		catch (Platform::Exception ^exception)
		{
			NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
			return;
		}

		info.GetReturnValue().Set(WrapBackgroundEnergyDiagnostics(winRtInstance));
    }


  


    static void ComputeTotalEnergyUsage(Nan::NAN_METHOD_ARGS_TYPE info)
    {
      HandleScope scope;

      if (info.Length() == 0)
      {
        try
        {
          unsigned __int64 result;
          result = ::Windows::System::Power::Diagnostics::BackgroundEnergyDiagnostics::ComputeTotalEnergyUsage();
          info.GetReturnValue().Set(Nan::New<Number>(static_cast<double>(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 ResetTotalEnergyUsage(Nan::NAN_METHOD_ARGS_TYPE info)
    {
      HandleScope scope;

      if (info.Length() == 0)
      {
        try
        {
          ::Windows::System::Power::Diagnostics::BackgroundEnergyDiagnostics::ResetTotalEnergyUsage();
          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 DeviceSpecificConversionFactorGetter(Local<String> property, const Nan::PropertyCallbackInfo<v8::Value> &info)
    {
      HandleScope scope;

      try 
      {
        double result = ::Windows::System::Power::Diagnostics::BackgroundEnergyDiagnostics::DeviceSpecificConversionFactor;
        info.GetReturnValue().Set(Nan::New<Number>(static_cast<double>(result)));
        return;
      }
      catch (Platform::Exception ^exception)
      {
        NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
        return;
      }
    }
    

  private:
    ::Windows::System::Power::Diagnostics::BackgroundEnergyDiagnostics^ _instance;
    static Persistent<FunctionTemplate> s_constructorTemplate;

    friend v8::Local<v8::Value> WrapBackgroundEnergyDiagnostics(::Windows::System::Power::Diagnostics::BackgroundEnergyDiagnostics^ wintRtInstance);
    friend ::Windows::System::Power::Diagnostics::BackgroundEnergyDiagnostics^ UnwrapBackgroundEnergyDiagnostics(Local<Value> value);
  };
  Persistent<FunctionTemplate> BackgroundEnergyDiagnostics::s_constructorTemplate;

  v8::Local<v8::Value> WrapBackgroundEnergyDiagnostics(::Windows::System::Power::Diagnostics::BackgroundEnergyDiagnostics^ 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>(BackgroundEnergyDiagnostics::s_constructorTemplate);
    return scope.Escape(Nan::NewInstance(Nan::GetFunction(localRef).ToLocalChecked(),_countof(args), args).ToLocalChecked());
  }

  ::Windows::System::Power::Diagnostics::BackgroundEnergyDiagnostics^ UnwrapBackgroundEnergyDiagnostics(Local<Value> value)
  {
     return BackgroundEnergyDiagnostics::Unwrap<BackgroundEnergyDiagnostics>(Nan::To<Object>(value).ToLocalChecked())->_instance;
  }

  void InitBackgroundEnergyDiagnostics(Local<Object> exports)
  {
    BackgroundEnergyDiagnostics::Init(exports);
  }

  class ForegroundEnergyDiagnostics : 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>("ForegroundEnergyDiagnostics").ToLocalChecked());
      localRef->InstanceTemplate()->SetInternalFieldCount(1);
      
                              
      Local<Object> constructor = Nan::To<Object>(Nan::GetFunction(localRef).ToLocalChecked()).ToLocalChecked();
	  Nan::SetMethod(constructor, "castFrom", CastFrom);

      Nan::SetMethod(constructor, "computeTotalEnergyUsage", ComputeTotalEnergyUsage);
      Nan::SetMethod(constructor, "resetTotalEnergyUsage", ResetTotalEnergyUsage);
      Nan::SetAccessor(constructor, Nan::New<String>("deviceSpecificConversionFactor").ToLocalChecked(), DeviceSpecificConversionFactorGetter);

      Nan::Set(exports, Nan::New<String>("ForegroundEnergyDiagnostics").ToLocalChecked(), constructor);
    }


    virtual ::Platform::Object^ GetObjectInstance() const override
    {
      return _instance;
    }

  private:
    
    ForegroundEnergyDiagnostics(::Windows::System::Power::Diagnostics::ForegroundEnergyDiagnostics^ 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::Power::Diagnostics::ForegroundEnergyDiagnostics^ winRtInstance;


      if (info.Length() == 1 && OpaqueWrapper::IsOpaqueWrapper(info[0]) &&
        NodeRT::Utils::IsWinRtWrapperOf<::Windows::System::Power::Diagnostics::ForegroundEnergyDiagnostics^>(info[0]))
      {
        try 
        {
          winRtInstance = (::Windows::System::Power::Diagnostics::ForegroundEnergyDiagnostics^) 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());

      ForegroundEnergyDiagnostics *wrapperInstance = new ForegroundEnergyDiagnostics(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::Power::Diagnostics::ForegroundEnergyDiagnostics^>(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::Power::Diagnostics::ForegroundEnergyDiagnostics^ winRtInstance;
		try
		{
			winRtInstance = (::Windows::System::Power::Diagnostics::ForegroundEnergyDiagnostics^) NodeRT::Utils::GetObjectInstance(info[0]);
		}
		catch (Platform::Exception ^exception)
		{
			NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
			return;
		}

		info.GetReturnValue().Set(WrapForegroundEnergyDiagnostics(winRtInstance));
    }


  


    static void ComputeTotalEnergyUsage(Nan::NAN_METHOD_ARGS_TYPE info)
    {
      HandleScope scope;

      if (info.Length() == 0)
      {
        try
        {
          unsigned __int64 result;
          result = ::Windows::System::Power::Diagnostics::ForegroundEnergyDiagnostics::ComputeTotalEnergyUsage();
          info.GetReturnValue().Set(Nan::New<Number>(static_cast<double>(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 ResetTotalEnergyUsage(Nan::NAN_METHOD_ARGS_TYPE info)
    {
      HandleScope scope;

      if (info.Length() == 0)
      {
        try
        {
          ::Windows::System::Power::Diagnostics::ForegroundEnergyDiagnostics::ResetTotalEnergyUsage();
          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 DeviceSpecificConversionFactorGetter(Local<String> property, const Nan::PropertyCallbackInfo<v8::Value> &info)
    {
      HandleScope scope;

      try 
      {
        double result = ::Windows::System::Power::Diagnostics::ForegroundEnergyDiagnostics::DeviceSpecificConversionFactor;
        info.GetReturnValue().Set(Nan::New<Number>(static_cast<double>(result)));
        return;
      }
      catch (Platform::Exception ^exception)
      {
        NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
        return;
      }
    }
    

  private:
    ::Windows::System::Power::Diagnostics::ForegroundEnergyDiagnostics^ _instance;
    static Persistent<FunctionTemplate> s_constructorTemplate;

    friend v8::Local<v8::Value> WrapForegroundEnergyDiagnostics(::Windows::System::Power::Diagnostics::ForegroundEnergyDiagnostics^ wintRtInstance);
    friend ::Windows::System::Power::Diagnostics::ForegroundEnergyDiagnostics^ UnwrapForegroundEnergyDiagnostics(Local<Value> value);
  };
  Persistent<FunctionTemplate> ForegroundEnergyDiagnostics::s_constructorTemplate;

  v8::Local<v8::Value> WrapForegroundEnergyDiagnostics(::Windows::System::Power::Diagnostics::ForegroundEnergyDiagnostics^ 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>(ForegroundEnergyDiagnostics::s_constructorTemplate);
    return scope.Escape(Nan::NewInstance(Nan::GetFunction(localRef).ToLocalChecked(),_countof(args), args).ToLocalChecked());
  }

  ::Windows::System::Power::Diagnostics::ForegroundEnergyDiagnostics^ UnwrapForegroundEnergyDiagnostics(Local<Value> value)
  {
     return ForegroundEnergyDiagnostics::Unwrap<ForegroundEnergyDiagnostics>(Nan::To<Object>(value).ToLocalChecked())->_instance;
  }

  void InitForegroundEnergyDiagnostics(Local<Object> exports)
  {
    ForegroundEnergyDiagnostics::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::Power::Diagnostics::InitBackgroundEnergyDiagnostics(target);
  NodeRT::Windows::System::Power::Diagnostics::InitForegroundEnergyDiagnostics(target);

  NodeRT::Utils::RegisterNameSpace("Windows.System.Power.Diagnostics", target);
}


NODE_MODULE(binding, init)