// 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 UI { namespace Composition { namespace Effects { 
  v8::Local<v8::Value> WrapSceneLightingEffect(::Windows::UI::Composition::Effects::SceneLightingEffect^ wintRtInstance);
  ::Windows::UI::Composition::Effects::SceneLightingEffect^ UnwrapSceneLightingEffect(Local<Value> value);
  





  class SceneLightingEffect : 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>("SceneLightingEffect").ToLocalChecked());
        localRef->InstanceTemplate()->SetInternalFieldCount(1);





          
            Nan::SetAccessor(localRef->PrototypeTemplate(), Nan::New<String>("name").ToLocalChecked(), NameGetter, NameSetter);
            Nan::SetAccessor(localRef->PrototypeTemplate(), Nan::New<String>("specularShine").ToLocalChecked(), SpecularShineGetter, SpecularShineSetter);
            Nan::SetAccessor(localRef->PrototypeTemplate(), Nan::New<String>("specularAmount").ToLocalChecked(), SpecularAmountGetter, SpecularAmountSetter);
            Nan::SetAccessor(localRef->PrototypeTemplate(), Nan::New<String>("normalMapSource").ToLocalChecked(), NormalMapSourceGetter, NormalMapSourceSetter);
            Nan::SetAccessor(localRef->PrototypeTemplate(), Nan::New<String>("diffuseAmount").ToLocalChecked(), DiffuseAmountGetter, DiffuseAmountSetter);
            Nan::SetAccessor(localRef->PrototypeTemplate(), Nan::New<String>("ambientAmount").ToLocalChecked(), AmbientAmountGetter, AmbientAmountSetter);

        Local<Object> constructor = Nan::To<Object>(Nan::GetFunction(localRef).ToLocalChecked()).ToLocalChecked();
        Nan::SetMethod(constructor, "castFrom", CastFrom);



        Nan::Set(exports, Nan::New<String>("SceneLightingEffect").ToLocalChecked(), constructor);
      }

      virtual ::Platform::Object^ GetObjectInstance() const override {
        return _instance;
      }

    private:

      SceneLightingEffect(::Windows::UI::Composition::Effects::SceneLightingEffect^ 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::UI::Composition::Effects::SceneLightingEffect^ winRtInstance;


      if (info.Length() == 1 && OpaqueWrapper::IsOpaqueWrapper(info[0]) &&
        NodeRT::Utils::IsWinRtWrapperOf<::Windows::UI::Composition::Effects::SceneLightingEffect^>(info[0])) {
        try {
          winRtInstance = (::Windows::UI::Composition::Effects::SceneLightingEffect^) NodeRT::Utils::GetObjectInstance(info[0]);
        } catch (Platform::Exception ^exception) {
          NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
          return;
        }
      }
      else if (info.Length() == 0)
      {
        try {
          winRtInstance = ref new ::Windows::UI::Composition::Effects::SceneLightingEffect();
        } 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());

      SceneLightingEffect *wrapperInstance = new SceneLightingEffect(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::UI::Composition::Effects::SceneLightingEffect^>(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::UI::Composition::Effects::SceneLightingEffect^ winRtInstance;
      try {
        winRtInstance = (::Windows::UI::Composition::Effects::SceneLightingEffect^) NodeRT::Utils::GetObjectInstance(info[0]);
      } catch (Platform::Exception ^exception) {
        NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
        return;
      }

      info.GetReturnValue().Set(WrapSceneLightingEffect(winRtInstance));
    }





    static void NameGetter(Local<String> property, const Nan::PropertyCallbackInfo<v8::Value> &info) {
      HandleScope scope;

      if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::UI::Composition::Effects::SceneLightingEffect^>(info.This())) {
        return;
      }

      SceneLightingEffect *wrapper = SceneLightingEffect::Unwrap<SceneLightingEffect>(info.This());

      try  {
        Platform::String^ result = wrapper->_instance->Name;
        info.GetReturnValue().Set(NodeRT::Utils::NewString(result->Data()));
        return;
      } catch (Platform::Exception ^exception) {
        NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
        return;
      }
    }
      
    static void NameSetter(Local<String> property, Local<Value> value, const Nan::PropertyCallbackInfo<void> &info) {
      HandleScope scope;

      if (!value->IsString()) {
        Nan::ThrowError(Nan::Error(NodeRT::Utils::NewString(L"Value to set is of unexpected type")));
        return;
      }

      if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::UI::Composition::Effects::SceneLightingEffect^>(info.This())) {
        return;
      }

      SceneLightingEffect *wrapper = SceneLightingEffect::Unwrap<SceneLightingEffect>(info.This());

      try {

        Platform::String^ winRtValue = ref new Platform::String(NodeRT::Utils::StringToWchar(v8::String::Value(v8::Isolate::GetCurrent(), value)));

        wrapper->_instance->Name = winRtValue;
      } catch (Platform::Exception ^exception) {
        NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
      }
    }
      
    static void SpecularShineGetter(Local<String> property, const Nan::PropertyCallbackInfo<v8::Value> &info) {
      HandleScope scope;

      if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::UI::Composition::Effects::SceneLightingEffect^>(info.This())) {
        return;
      }

      SceneLightingEffect *wrapper = SceneLightingEffect::Unwrap<SceneLightingEffect>(info.This());

      try  {
        float result = wrapper->_instance->SpecularShine;
        info.GetReturnValue().Set(Nan::New<Number>(static_cast<double>(result)));
        return;
      } catch (Platform::Exception ^exception) {
        NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
        return;
      }
    }
      
    static void SpecularShineSetter(Local<String> property, Local<Value> value, const Nan::PropertyCallbackInfo<void> &info) {
      HandleScope scope;

      if (!value->IsNumber()) {
        Nan::ThrowError(Nan::Error(NodeRT::Utils::NewString(L"Value to set is of unexpected type")));
        return;
      }

      if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::UI::Composition::Effects::SceneLightingEffect^>(info.This())) {
        return;
      }

      SceneLightingEffect *wrapper = SceneLightingEffect::Unwrap<SceneLightingEffect>(info.This());

      try {

        float winRtValue = static_cast<float>(Nan::To<double>(value).FromMaybe(0.0));

        wrapper->_instance->SpecularShine = winRtValue;
      } catch (Platform::Exception ^exception) {
        NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
      }
    }
      
    static void SpecularAmountGetter(Local<String> property, const Nan::PropertyCallbackInfo<v8::Value> &info) {
      HandleScope scope;

      if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::UI::Composition::Effects::SceneLightingEffect^>(info.This())) {
        return;
      }

      SceneLightingEffect *wrapper = SceneLightingEffect::Unwrap<SceneLightingEffect>(info.This());

      try  {
        float result = wrapper->_instance->SpecularAmount;
        info.GetReturnValue().Set(Nan::New<Number>(static_cast<double>(result)));
        return;
      } catch (Platform::Exception ^exception) {
        NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
        return;
      }
    }
      
    static void SpecularAmountSetter(Local<String> property, Local<Value> value, const Nan::PropertyCallbackInfo<void> &info) {
      HandleScope scope;

      if (!value->IsNumber()) {
        Nan::ThrowError(Nan::Error(NodeRT::Utils::NewString(L"Value to set is of unexpected type")));
        return;
      }

      if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::UI::Composition::Effects::SceneLightingEffect^>(info.This())) {
        return;
      }

      SceneLightingEffect *wrapper = SceneLightingEffect::Unwrap<SceneLightingEffect>(info.This());

      try {

        float winRtValue = static_cast<float>(Nan::To<double>(value).FromMaybe(0.0));

        wrapper->_instance->SpecularAmount = winRtValue;
      } catch (Platform::Exception ^exception) {
        NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
      }
    }
      
    static void NormalMapSourceGetter(Local<String> property, const Nan::PropertyCallbackInfo<v8::Value> &info) {
      HandleScope scope;

      if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::UI::Composition::Effects::SceneLightingEffect^>(info.This())) {
        return;
      }

      SceneLightingEffect *wrapper = SceneLightingEffect::Unwrap<SceneLightingEffect>(info.This());

      try  {
        ::Windows::Graphics::Effects::IGraphicsEffectSource^ result = wrapper->_instance->NormalMapSource;
        info.GetReturnValue().Set(NodeRT::Utils::CreateExternalWinRTObject("Windows.Graphics.Effects", "IGraphicsEffectSource", result));
        return;
      } catch (Platform::Exception ^exception) {
        NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
        return;
      }
    }
      
    static void NormalMapSourceSetter(Local<String> property, Local<Value> value, const Nan::PropertyCallbackInfo<void> &info) {
      HandleScope scope;

      if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::Graphics::Effects::IGraphicsEffectSource^>(value)) {
        Nan::ThrowError(Nan::Error(NodeRT::Utils::NewString(L"Value to set is of unexpected type")));
        return;
      }

      if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::UI::Composition::Effects::SceneLightingEffect^>(info.This())) {
        return;
      }

      SceneLightingEffect *wrapper = SceneLightingEffect::Unwrap<SceneLightingEffect>(info.This());

      try {

        ::Windows::Graphics::Effects::IGraphicsEffectSource^ winRtValue = dynamic_cast<::Windows::Graphics::Effects::IGraphicsEffectSource^>(NodeRT::Utils::GetObjectInstance(value));

        wrapper->_instance->NormalMapSource = winRtValue;
      } catch (Platform::Exception ^exception) {
        NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
      }
    }
      
    static void DiffuseAmountGetter(Local<String> property, const Nan::PropertyCallbackInfo<v8::Value> &info) {
      HandleScope scope;

      if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::UI::Composition::Effects::SceneLightingEffect^>(info.This())) {
        return;
      }

      SceneLightingEffect *wrapper = SceneLightingEffect::Unwrap<SceneLightingEffect>(info.This());

      try  {
        float result = wrapper->_instance->DiffuseAmount;
        info.GetReturnValue().Set(Nan::New<Number>(static_cast<double>(result)));
        return;
      } catch (Platform::Exception ^exception) {
        NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
        return;
      }
    }
      
    static void DiffuseAmountSetter(Local<String> property, Local<Value> value, const Nan::PropertyCallbackInfo<void> &info) {
      HandleScope scope;

      if (!value->IsNumber()) {
        Nan::ThrowError(Nan::Error(NodeRT::Utils::NewString(L"Value to set is of unexpected type")));
        return;
      }

      if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::UI::Composition::Effects::SceneLightingEffect^>(info.This())) {
        return;
      }

      SceneLightingEffect *wrapper = SceneLightingEffect::Unwrap<SceneLightingEffect>(info.This());

      try {

        float winRtValue = static_cast<float>(Nan::To<double>(value).FromMaybe(0.0));

        wrapper->_instance->DiffuseAmount = winRtValue;
      } catch (Platform::Exception ^exception) {
        NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
      }
    }
      
    static void AmbientAmountGetter(Local<String> property, const Nan::PropertyCallbackInfo<v8::Value> &info) {
      HandleScope scope;

      if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::UI::Composition::Effects::SceneLightingEffect^>(info.This())) {
        return;
      }

      SceneLightingEffect *wrapper = SceneLightingEffect::Unwrap<SceneLightingEffect>(info.This());

      try  {
        float result = wrapper->_instance->AmbientAmount;
        info.GetReturnValue().Set(Nan::New<Number>(static_cast<double>(result)));
        return;
      } catch (Platform::Exception ^exception) {
        NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
        return;
      }
    }
      
    static void AmbientAmountSetter(Local<String> property, Local<Value> value, const Nan::PropertyCallbackInfo<void> &info) {
      HandleScope scope;

      if (!value->IsNumber()) {
        Nan::ThrowError(Nan::Error(NodeRT::Utils::NewString(L"Value to set is of unexpected type")));
        return;
      }

      if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::UI::Composition::Effects::SceneLightingEffect^>(info.This())) {
        return;
      }

      SceneLightingEffect *wrapper = SceneLightingEffect::Unwrap<SceneLightingEffect>(info.This());

      try {

        float winRtValue = static_cast<float>(Nan::To<double>(value).FromMaybe(0.0));

        wrapper->_instance->AmbientAmount = winRtValue;
      } catch (Platform::Exception ^exception) {
        NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
      }
    }
      


    private:
      ::Windows::UI::Composition::Effects::SceneLightingEffect^ _instance;
      static Persistent<FunctionTemplate> s_constructorTemplate;

      friend v8::Local<v8::Value> WrapSceneLightingEffect(::Windows::UI::Composition::Effects::SceneLightingEffect^ wintRtInstance);
      friend ::Windows::UI::Composition::Effects::SceneLightingEffect^ UnwrapSceneLightingEffect(Local<Value> value);
  };

  Persistent<FunctionTemplate> SceneLightingEffect::s_constructorTemplate;

  v8::Local<v8::Value> WrapSceneLightingEffect(::Windows::UI::Composition::Effects::SceneLightingEffect^ 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>(SceneLightingEffect::s_constructorTemplate);
    return scope.Escape(Nan::NewInstance(Nan::GetFunction(localRef).ToLocalChecked(),_countof(args), args).ToLocalChecked());
  }

  ::Windows::UI::Composition::Effects::SceneLightingEffect^ UnwrapSceneLightingEffect(Local<Value> value) {
     return SceneLightingEffect::Unwrap<SceneLightingEffect>(Nan::To<Object>(value).ToLocalChecked())->_instance;
  }

  void InitSceneLightingEffect(Local<Object> exports) {
    SceneLightingEffect::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::UI::Composition::Effects::InitSceneLightingEffect(target);


  NodeRT::Utils::RegisterNameSpace("Windows.UI.Composition.Effects", target);
}



NODE_MODULE(binding, init)
