/**
 * Taken from
 * https://developer.chrome.com/docs/extensions/reference/offscreen/
 * and modified
 */

let creating; // A global promise to avoid concurrency issues
async function setupOffscreenDocument() {
  let path = `offScreen.html`
  // Check all windows controlled by the service worker to see if one 
  // of them is the offscreen document with the given path
  const offscreenUrl = chrome.runtime.getURL(path);
  const matchedClients = await clients.matchAll();
  for (const client of matchedClients) {
    if (client.url === offscreenUrl) {
      return;
    }
  }

  // create offscreen document
  if (creating) {
    await creating;
  } else {
    creating = chrome.offscreen.createDocument({
      url: path,
      reasons: ['DOM_PARSER'],
      justification: 'append next page',
    });
    await creating;
    creating = null;
  }
}

export default setupOffscreenDocument;