// Copyright © 2022 BytePlusRTC All rights reserved.
// SPDX-License-Identifier: MIT

package com.volcengine.reactnative.vertc;

import com.facebook.react.bridge.Callback;
import com.facebook.react.bridge.ReactApplicationContext;
import com.volcengine.VolcApiEngine.IEventReceiver;
import com.volcengine.VolcApiEngine.VolcApiEngine;
import com.volcengine.reactnative.vertc.events.ClassHelper;


public class VertcImpl {
  
  public VolcApiEngine apiEngine = null;
  private ReactApplicationContext moduleContext;
  private IEventReceiver module;

  public static final String NAME = "Vertc";
  public static final String EVENT_NAME = "VertcModule:onEvent";
  VertcImpl(ReactApplicationContext context, IEventReceiver module ) {
    ClassHelper.init();
    this.moduleContext = context;
    this.module = module;
  }
  
  public boolean newApiEngine() {
    if (apiEngine == null) {
      apiEngine = new VolcApiEngine(moduleContext, this.module);
      NativeVariableManager.init(apiEngine.msgClient, moduleContext);
      return true;
    }
    return false;
  }
    
  public String callApiSync(String params) {
    try {
      newApiEngine();
      return this.apiEngine.callApi(params);
    } catch (Exception e) {
      e.printStackTrace();
      throw new RuntimeException(e);
    }
  }
  
  public void callApi(String params, Callback callback) {
    try {
      newApiEngine();
      // 获取主线程处理器
      android.os.Handler mainHandler =
        new android.os.Handler(android.os.Looper.getMainLooper());

      // 在主线程上执行 API 调用
      mainHandler.post(() -> {
        try {
          this.apiEngine.callApi(
            params, (res) -> {
              callback.invoke(res.toJsonString());
            });
        } catch (Exception e) {
          e.printStackTrace();
        }
      });
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
}
