import { createContext, useContext } from 'react';

import { mountTag } from '@/modules/@common/app/helpers';

export const getPlayerEndpoint = () => process.env.APP_PLAYER_WIDGET_URL;

export const getPlaylistApiEndpoint = () => process.env.APP_PLAYER_PLAYLIST_URL;

export const getPlayerConfigCdnEndpoint = (publisherSlug, playerName) => {
  const configUrl = process.env.APP_PLAYER_CONFIG_URL;

  return `${configUrl}${publisherSlug}/${playerName}/conf.js?cb=${Date.now()}`;
};

export const getDirtyEvalObjectFromString = (response) =>
  // eslint-disable-next-line no-eval
  eval(`(function(){ return ${response.replace(/ac_lre_conf =/, '')}})()`);

const providers = {};
export const setContext = (instanceKey) => {
  if (!providers[instanceKey]) {
    providers[instanceKey] = createContext({});
  }
};
export const getContext = (instanceKey) => providers[instanceKey];
export const deleteContext = (instanceKey) => {
  delete providers[instanceKey];
};

export const getCustomWidgetId = (instanceKey) => `${instanceKey}==[${Date.now().toString(36)}]`;

export const usePlayerWidget = (instanceKey) => useContext(providers[instanceKey]);

export const fetchConfig = (publisherSlug, playerName, confOverride) =>
  new Promise((resolve, reject) => {
    const script = mountTag('script', {
      props: {
        src: getPlayerConfigCdnEndpoint(publisherSlug, playerName),
      },
      appendContainer: document.body,
      withoutUnmount: true,
    });

    script.addEventListener('load', () => {
      window.ac_lre_conf_override = {
        ...confOverride({ ...window.ac_lre_conf }),
        lre_export_for_demo: true,
        lre_playlistApiEndpoint: getPlaylistApiEndpoint(),
      };

      script.remove();
      resolve();
    });

    script.addEventListener('error', () => {
      script.remove();
      reject();
    });
  });
