package com.volcengine.reactnative.veplayer;

import com.facebook.react.bridge.Callback;
import com.facebook.react.bridge.ReactApplicationContext;

import com.ss.ttvideoengine.strategy.StrategyManager;
import com.volcengine.VolcApiEngine.IEventReceiver;
import com.volcengine.VolcApiEngine.VolcApiEngine;
import com.volcengine.reactnative.veplayer.events.ClassHelper;

/**
 * Centralized implementation for VeplayerModule shared logic.
 * Mirrors the pattern of VeLivePullImpl: holding VolcApiEngine instance,
 * initializing NativeVariableManager and handling callApi/callApiSync.
 */
public class VeplayerImpl {
  private VolcApiEngine apiEngine = null;
  public final ReactApplicationContext moduleContext;
  private final IEventReceiver module;

  public static final String NAME = "VeplayerModule";
  public static final String EVENT_NAME = "VeplayerModule:onEvent";

  VeplayerImpl(ReactApplicationContext context, IEventReceiver module) {
    this.moduleContext = context;
    this.module = module;
    // Register event related helpers/classes
    ClassHelper.init();
  }

  public boolean newApiEngine() {
    if (apiEngine == null) {
      apiEngine = new VolcApiEngine(moduleContext, this.module);
      NativeVariableManager.init(apiEngine.msgClient, moduleContext);

      return true;
    }
    return false;
  }

  public boolean destroyApiEngine() {
    if (apiEngine != null) {
      try {
        apiEngine.msgClient.proto.dispose();
      } catch (Throwable ignored) {
      }
      apiEngine = null;
    }

    return true;
  }

  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();
      // Ensure execution on main thread
      android.os.Handler mainHandler = new android.os.Handler(android.os.Looper.getMainLooper());
      mainHandler.post(() -> {
        try {
          this.apiEngine.callApi(params, (res) -> {
            callback.invoke(res.toJsonString());
          });
        } catch (Exception e) {
          e.printStackTrace();
        }
      });
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
}
