import { NativeModules } from 'react-native';
import type { ImpressionEvent } from './Event';
import { TapsellEventEmitter } from './TapsellEventEmitter';

/** @internal */
class MediationEventListener {
  private readonly tapsellMediationEmitter: TapsellEventEmitter;

  constructor() {
    this.tapsellMediationEmitter = new TapsellEventEmitter(
      NativeModules.RNTapsellMediation
    );
  }

  public registerAdImpressionListener(
    callback: (event: ImpressionEvent) => void
  ) {
    this.tapsellMediationEmitter?.addListener(AndroidAPIs.Impression, callback);
  }

  public registerAdClickListener(callback: (event: ImpressionEvent) => void) {
    this.tapsellMediationEmitter?.addListener(AndroidAPIs.Click, callback);
  }
  public registerAdRewardListener(callback: (event: ImpressionEvent) => void) {
    this.tapsellMediationEmitter?.addListener(AndroidAPIs.Reward, callback);
  }
  public registerAdCloseListener(callback: (event: ImpressionEvent) => void) {
    this.tapsellMediationEmitter?.addListener(AndroidAPIs.Close, callback);
  }
  public registerAdShowFailureListener(
    callback: (event: ImpressionEvent) => void
  ) {
    this.tapsellMediationEmitter?.addListener(
      AndroidAPIs.ShowFailure,
      callback
    );
  }

  public registerLegacyNativeAdShowListener(
    callback: (event: ImpressionEvent) => void
  ) {
    this.tapsellMediationEmitter?.addListener('onLegacyNativeAdShow', callback);
  }

  public registerLegacyNativeAdDestroyListener(
    callback: (event: ImpressionEvent) => void
  ) {
    this.tapsellMediationEmitter?.addListener(
      'onLegacyNativeAdDestroy',
      callback
    );
  }
}

const AndroidAPIs = {
  Impression: 'onAdImpression',
  Click: 'onAdClicked',
  Reward: 'onUserRewarded',
  Close: 'onAdClosed',
  ShowFailure: 'onFailedShow',
};

/** @internal */
export const _mediationEventListenerInstance = new MediationEventListener();
