/* eslint-disable no-restricted-properties */
/* eslint-disable no-caller */
/* global arguments */
import { sendMessageTabId } from '@/browser/tab';
import { browserOnMessage } from '@/browser/api';
import { genUuid } from '@/lib/utils/utils';
import { EVENT_TAB_FETCH_URL } from '@/bridge/config/event';

const senderTabService = async (tabId, event, data = {}) => {
  let isResponsed = false;
  const payload = {
    data,
    _id: genUuid(),
    event,
  };

  return new Promise(async (resolve) => {
    const responser = (request, sender, sendResponse) => {
      if (!isResponsed) {
        if (request._id === payload._id) {
          resolve(request.data);
          isResponsed = true;
          try {
            browserOnMessage.removeListener(arguments.callee);
          } catch (error) {}
        }
        sendResponse(true);
        return true;
      }
    };

    browserOnMessage.addListener(responser);

    sendMessageTabId(tabId, payload);
  });
};

/**
 *
 * @param {number} tabId
 * @param {object} payload
 * @param {RequestMethod} payload.method
 * @param {string} payload.url
 * @param {object} [payload.body]
 * @returns
 */
export const bridgeTabFetchShopeeUrl = async (tabId, payload = {}) => senderTabService(tabId, EVENT_TAB_FETCH_URL, payload);
