/* eslint-disable no-undef */
import './ping.js';

let allConnectedPorts = [];

async function createOffscreen() {
  if (await chrome.offscreen.hasDocument()) return;
  await chrome.offscreen.createDocument({
    url: 'offscreen.html',
    reasons: ['AUDIO_PLAYBACK'],
    justification: 'Play pomodoro clock alert audio', // details for using the API
  });
}

async function playAlertAudio(audioUrl) {
  await createOffscreen();
  await chrome.runtime.sendMessage({ play: { source: audioUrl, volume: 1 } });
}

chrome.runtime.onConnect.addListener(async (port) => {
  if (/^wowTabSync/.test(port.name) != null) {
    allConnectedPorts.push(port);
    console.log('connected', port.name);
    port.onDisconnect.addListener(() => {
      console.log('disconnected port', port.name);
      allConnectedPorts = allConnectedPorts.filter((p) => p !== port);
    });

    port.onMessage.addListener((msg) => {
      console.log('received message', msg);
      if (msg.type === 'triggerAction') {
        allConnectedPorts.forEach((p) => {
          try {
          // Do not send message to self port
            if (p !== port) {
              p.postMessage({
                type: 'syncState',
                action: msg.action,
              });
            }
          } catch (e) {
            console.log('sw error', e.stack);
            console.log('remove', p.name, 'from ports');
            allConnectedPorts = allConnectedPorts.filter((pitem) => pitem !== p);
          }
        });
      } else if (msg.type === 'playAlertAudio') {
        playAlertAudio(msg.audioUrl);
      }
    });
  }
});

chrome.action.onClicked.addListener(() => {
  chrome.tabs.create({ url: chrome.runtime.getURL('index.html') });
});
