package com.volcengine.velive.rn.pull;

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.velive.rn.pull.autogen.MethodSignature;

//LivePullProxy 代理 TurboModule 和 NativeModule，消息统一聚合
public class VeLivePullImpl {
  
  private VolcApiEngine apiEngine = null;
  private ReactApplicationContext moduleContext;
  private IEventReceiver module;

  public static final String NAME = "VeLivePull";
  public static final String EVENT_NAME = "VeLivePull:onEvent";
  VeLivePullImpl(ReactApplicationContext context, IEventReceiver module ) {
    MethodSignature.init();
    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();
    }
  }
}
