/**
 * This is a scheduled batched register mechanism for resolving blue hyperlinks while the page is idle.
 * i.e. SharePoint tenants with the same hostname will be grouped together before the register is made.
 */

import { useCallback, useRef } from 'react';
var batchQueue = new Map();
var batchTimeouts = new Map();
var BATCH_DELAY = 250;
var executeBatch = function executeBatch(hostname) {
  var items = batchQueue.get(hostname) || [];
  if (items.length === 0) {
    return;
  }
  batchQueue.delete(hostname);
  batchTimeouts.delete(hostname);
  items.forEach(function (_ref) {
    var register = _ref.register,
      resolve = _ref.resolve,
      reject = _ref.reject;
    register().then(resolve).catch(reject);
  });
};
var addToBatch = function addToBatch(hostname, item) {
  if (!batchQueue.has(hostname)) {
    batchQueue.set(hostname, []);
  }
  batchQueue.get(hostname).push(item);
  if (batchTimeouts.has(hostname)) {
    clearTimeout(batchTimeouts.get(hostname));
  }
  batchTimeouts.set(hostname, setTimeout(function () {
    executeBatch(hostname);
  }, BATCH_DELAY));
};
export var useScheduledRegister = function useScheduledRegister(href, register) {
  var isScheduled = useRef(false);
  var scheduledRegister = useCallback(function () {
    if (!href || !register || isScheduled.current) {
      return Promise.resolve();
    }
    isScheduled.current = true;
    return new Promise(function (_resolve, _reject) {
      var scheduleRegister = function scheduleRegister() {
        try {
          var hostname = new URL(href).hostname;
          addToBatch(hostname, {
            href: href,
            register: register,
            resolve: function resolve(value) {
              isScheduled.current = false;
              _resolve(value);
            },
            reject: function reject(error) {
              isScheduled.current = false;
              _reject(error);
            }
          });
        } catch (error) {
          isScheduled.current = false;
          register().then(_resolve).catch(_reject);
        }
      };
      if (typeof window !== 'undefined') {
        if ('requestIdleCallback' in window) {
          window.requestIdleCallback(scheduleRegister);
        } else {
          setTimeout(scheduleRegister, 0);
        }
      } else {
        scheduleRegister();
      }
    });
  }, [href, register]);
  return scheduledRegister;
};