import { AdPlatformAdapter } from "../types";
import { openWithMraidOrWindow, setupMraidCustomClose } from "./helpers";
import { getStoreUrl } from "./storeUrls";

export function createUnityAdapter(): AdPlatformAdapter {
  let ready = false;
  let started = false;
  let ended = false;

  function notifyReady() {
    if (ready) return;
    ready = true;
    window.dapi?.gameReady();
  }

  return {
    platform: "unity",

    init() {
      setupMraidCustomClose();
    },

    onResourcesLoaded() {
      if (!window.dapi) return;
      if (window.dapi.isReady()) {
        notifyReady();
      } else {
        window.dapi.addEventListener("ready", notifyReady);
      }
    },

    onGameStart() {
      if (started) return;
      started = true;
    },

    onGameEnd() {
      if (ended) return;
      ended = true;
    },

    openStore() {
      openWithMraidOrWindow(getStoreUrl());
    },

    shouldUseCustomLoading() {
      return true;
    },

    shouldShowAdBadge() {
      return true;
    },
  };
}

export const adPlatform = createUnityAdapter();
