package com.reactnativetheoremreachld;

import androidx.annotation.NonNull;

import com.facebook.react.bridge.Arguments;
import com.facebook.react.bridge.Promise;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.ReactContextBaseJavaModule;
import com.facebook.react.bridge.ReactMethod;
import com.facebook.react.bridge.WritableMap;
import com.facebook.react.module.annotations.ReactModule;
import com.facebook.react.modules.core.DeviceEventManagerModule;

import theoremreach.com.theoremreach.TheoremReach;
import theoremreach.com.theoremreach.TheoremReachSurveyListener;

@ReactModule(name = TheoremReachLdModule.NAME)
public class TheoremReachLdModule extends ReactContextBaseJavaModule {
  public static final String NAME = "TheoremReachLd";

  public TheoremReachLdModule(ReactApplicationContext reactContext) {
    super(reactContext);
  }

  private void sendEvent(String eventName, String value) {
    WritableMap params = Arguments.createMap();
    params.putString("value", value);

    getReactApplicationContext()
      .getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class)
      .emit(eventName, params);
  }

  TheoremReachSurveyListener theoremReachSurveyListener = new TheoremReachSurveyListener() {
    @Override
    public void onRewardCenterClosed() {
      sendEvent("onRewardCenterClosed", "onRewardCenterClosed");
    }

    @Override
    public void onRewardCenterOpened() {
      sendEvent("onRewardCenterOpened", "onRewardCenterOpened");
    }
  };


  @Override
  @NonNull
  public String getName() {
    return NAME;
  }

  // Example method
  // See https://reactnative.dev/docs/native-modules-android
  @ReactMethod
  public void initialize(String apiKey, String userId) {
    TheoremReach.getInstance().setTheoremReachSurveyListener(theoremReachSurveyListener);
    TheoremReach.initWithApiKeyAndUserIdAndActivityContext(apiKey, userId, getCurrentActivity());
  }

  @ReactMethod
  public void show(String placementId) {
    TheoremReach.getInstance().showRewardCenter(placementId);
  }

  @ReactMethod
  public void isSurveyAvailable(Promise promise) {
    promise.resolve(TheoremReach.getInstance().isSurveyAvailable());
  }


}
