let url_path = window?.url_path || '';
const document_title = 'Wazzup - общий чат',
  basic_image = `${url_path}/images/favicon.png`,
  new_msg_image = `${url_path}/stocks/images/message_dots.svg`;

/**
 * Обновление подписи вкладки.
 * @param {number} msg_count
 */
function updatePageTitle(msg_count) {
  let image = 1,
    msg = `Новое сообщение (${msg_count})`,
    link = document.querySelector("link[rel~='icon']");

  clearInterval(window.interval);
  window.interval = null;
  window.onmousemove = null;
  document.title = document_title;

  if (msg_count === 0) {
    link.href = basic_image;
    return;
  }

  window.interval = setInterval(function() {
    document.title = document.title == msg
      ? document_title
      : msg;

      image = image === 1 ? 2 : 1;
      link.href = image === 2 ? new_msg_image : basic_image;
  }, 1000);
}

export default function(settings) {
  // console.log(settings);

  function handler() {
    if (this.readyState === this.DONE) {
      if (this.status === 200) {
        document.querySelector('#wazzup_iframe').src = this.response.url;
        document.querySelector('#wazzup_iframe').onload = onLoadHandler;
      } else {
        console.error('Request failed', this);
      }
    }
  }

  function onLoadHandler() {
    const connectOptions = {
      path: '/ws-counters/',
      transports: ['websocket', 'polling']
    };

    fetch(
      `https://integrations.wazzup24.com/counters/ws_host/api_v3/${settings.api_key}`
    )
    .then((response) => response.json())
    .then((data) => {
      const { host } = data;

      // Подключаемся при помощи socket.io
      const client = io(`https://${host}`, connectOptions);

      // Слушаем событие 'connect'
      client.on('connect', () => {
        // Завершаем подключение: транслируем событие 'counterConnecting',
        // в котором передаем данные клиента
        client.emit('counterConnecting', {
          type: 'api_v3',
          apiKey: settings?.api_key || '',
          userId: settings?.user?.id || '',
        });
      });

      // Подтверждение подключения
      // client.on(
      //   'counterConnected',
      //   () => console.log('Connected to Wazzup notifications!')
      // );

      // Обновление счетчика неотвеченных
      client.on('counterUpdate', (data) => {
        // console.log(data);
        const { counter, counterV2 } = data;
        updatePageTitle(Number(counterV2));
      });
    })
    .catch((error) => console.log('Connection error', error));
  }

  let xhr = new XMLHttpRequest();
  xhr.open('POST', 'https://api.wazzup24.com/v3/iframe');
  xhr.onreadystatechange = handler;
  xhr.responseType = 'json';
  [
    ['Authorization', `Bearer ${settings?.api_key}`],
    ['Content-Type', 'application/json']
  ].forEach(function (header) {
    xhr.setRequestHeader(header[0], header[1]);
  });
  xhr.send(JSON.stringify({
    scope: 'global',
    user: {
      id:   settings?.user?.id || '',
      name: settings?.user?.name || '',
    }
  }));
}
