'use strict';
// serviceworker.js 2026/02/14, chromium manifest v3
// for HoreRisu V4.0, Tonchinkan Office (C)2011-2026, All Rights Reserved
// https://www.tonchinkan.biz/

{

  //----------------------------------------------------------

  // https://developer.chrome.com/docs/extensions/reference/api/offscreen
  let creating; // A global promise to avoid concurrency issues
  async function setupOffscreenDocument(path) {
    // 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 existingContexts = await chrome.runtime.getContexts({
      contextTypes: ['OFFSCREEN_DOCUMENT'],
      documentUrls: [offscreenUrl]
    });

    if (existingContexts.length > 0) {
      return;
    }

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

  //----------------------------------------------------------

  //  Create contextMenus
  const ID_LINK_URL = "menu1"
  const ID_SRC_URL  = "menu2"

  // OnInstalled
  chrome.runtime.onInstalled.addListener(function () {

    // Current Link Target
    chrome.contextMenus.create({
        "id": ID_LINK_URL,
        "title": "HoreRisu Link Target",
        "type": "normal",
        "contexts": ["link"]
      })

    // Current Picture URL
    chrome.contextMenus.create({
        "id": ID_SRC_URL,
        "title": "HoreRisu Picture",
        "type": "normal",
        "contexts": ["image"]
      })
  });

  chrome.contextMenus.onClicked.addListener(async (info) => {
    await setupOffscreenDocument('offscreen.html');
    switch (info.menuItemId) {

      // Current Link Target
      case ID_LINK_URL:
        let Promise1 = chrome.runtime.sendMessage({
          target: 'offscreen',
          data: decodeURI(info.linkUrl)
          });
        Promise1
          .then((response)=> {
            })
          .catch((error)=> {
            })
        break;

      // Current Picture URL
      case ID_SRC_URL:
        let Promise2 = chrome.runtime.sendMessage({
          target: 'offscreen',
          data: decodeURI(info.srcUrl)
          });
        Promise2
          .then((response)=> {
            })
          .catch((error)=> {
            })
        break;
      }
    }
  )

  //----------------------------------------------------------
}
