// Copyright (c) 2023 Tencent. All rights reserved.
// Author: felixyyan

#include "tmg_delegate_bindings.h"
#include <string>
#include "application/ApplicationManager.h"
#include "bindings/jswrapper/SeApi.h"

void TMGDelegateBindings::setJsTMGDelegate(const se::Value& callback) {
  delegate_js_callback_ = std::make_shared<se::Value>(callback);
}

void RunOnCocosThread(const std::function<void()>& func) {
  if (CC_CURRENT_APPLICATION() == nullptr) {
    return;
  }
  CC_CURRENT_ENGINE()->getScheduler()->performFunctionInCocosThread(func);
}

void TMGDelegateBindings::OnEvent(ITMG_MAIN_EVENT_TYPE type, const char* data) {
  std::string tmp_data = data;
  auto delegate_js_callback = delegate_js_callback_;
  RunOnCocosThread([type, tmp_data, delegate_js_callback]() {
    se::AutoHandleScope hs;
    se::Value method;

    if (!delegate_js_callback || !delegate_js_callback->isObject()) {
      return;
    }

    if (delegate_js_callback->toObject()->getProperty("OnEvent", &method)) {
      if (!method.isObject() || !method.toObject()->isFunction()) {
        return;
      }

      se::Value js_type, js_data;
      nativevalue_to_se(type, js_type, nullptr);
      nativevalue_to_se(tmp_data, js_data, nullptr);
      se::ValueArray args{js_type, js_data};
      method.toObject()->call(args, delegate_js_callback->toObject());
    }
  });
}
