import {
  findPluginByIdentifier,
  findPluginByType,
} from "@applicaster/zapp-react-native-utils/pluginUtils";

import { CHROMECAST_PLUGIN_ID, YOUTUBE_PLUGIN_ID } from "./const";
import { omit } from "@applicaster/zapp-react-native-utils/utils";
import { getXray } from "@applicaster/zapp-react-native-utils/logger";

const { Logger } = getXray();

const logger = new Logger(
  "QuickBrick",
  "packages/zapp-react-native-ui-components/Components/HandlePlayable"
);

const getPlayerModuleProperties = (PlayerModule: ZappPlugin) => {
  if (PlayerModule?.Component && typeof PlayerModule.Component === "object") {
    return omit(["Component"], PlayerModule);
  }

  return {};
};

export const getPlayerWithModuleProperties = (
  PlayerModule: ZappPlugin
): [ZappPlugin, PlayerModuleProperties] => {
  return [
    PlayerModule?.Component || PlayerModule,
    getPlayerModuleProperties(PlayerModule),
  ];
};

export const findCastPlugin = (plugins: ZappPlugin[]) =>
  findPluginByIdentifier(CHROMECAST_PLUGIN_ID, plugins, true) || {};

export const findYoutubePlugin = (plugins: ZappPlugin[]) =>
  findPluginByIdentifier(YOUTUBE_PLUGIN_ID, plugins, true) || {};

export const getPlayer = (
  item: ZappEntry,
  {
    plugins,
    contentTypes,
    rivers,
    appData: { layoutVersion },
  }: {
    plugins: ZappPlugin[];
    contentTypes: Record<string, any>;
    rivers: Record<string, any>;
    appData: { layoutVersion: string };
  }
): [ZappPlugin, PlayerModuleProperties] => {
  let PlayerModule;

  if (layoutVersion === "v2") {
    const screen_id = contentTypes?.[item?.type?.value]?.screen_id;
    const type = rivers?.[screen_id]?.type;

    if (type) {
      PlayerModule = findPluginByIdentifier(type, plugins)?.module;

      if (!PlayerModule) {
        logger.error({
          message:
            "PlayerModule is undefined – type mapping may be wrong or type not set for player",
          data: {
            type,
            screen_id,
            item_type_value: item?.type?.value,
          },
        });

        return [null, {}];
      }

      return getPlayerWithModuleProperties(PlayerModule);
    }
  }

  // TODO: Probably should be removed, Youtube plugin is deprecated
  if (item?.content?.type === "youtube-id") {
    PlayerModule = findYoutubePlugin(plugins)?.module;

    return getPlayerWithModuleProperties(PlayerModule);
  }

  PlayerModule = findPluginByType(
    "playable",
    (plugins as any[]).filter(
      ({ identifier }: { identifier: string }) =>
        identifier !== YOUTUBE_PLUGIN_ID
    )
  );

  if (!PlayerModule) {
    logger.error({
      message: "PlayerModule is undefined – playable plugin not found",
    });

    return [null, {}];
  }

  return getPlayerWithModuleProperties(PlayerModule);
};
