// index.js
// Copyright (C) 2022 DTP Technologies, LLC
// License: Apache-2.0

'use strict';

const DTP_COMPONENT = { name: 'Site', slug: 'site' };

const dtp = window. dtp = window.dtp || { };

import DtpSiteApp from './site-app.js';
import DtpWebLog from 'dtp/dtp-log.js';
// import UIkit from 'uikit';

/**
 * Monkeypatch to count characters instead of .length's code point count.
 * @returns character count of string
 */
String.prototype.charCount = function () {
  const splat = [...this];
  return splat.length;
};

window.addEventListener('load', async ( ) => {
  // application console log
  dtp.log = new DtpWebLog(DTP_COMPONENT);

  // service worker
  if ('serviceWorker' in navigator) {
    try {
      dtp.registration = await navigator.serviceWorker.register('/dist/js/service_worker.min.js');
      dtp.log.info('load', 'service worker startup complete', { scope: dtp.registration.scope });
    } catch (error) {
      console.log('service worker startup failed', { error });
      // UIkit.modal.alert(`Service worker startup failed: ${error.message}`);
    }
  }
  
  dtp.app = new DtpSiteApp(dtp.user);
  if (dtp.user && dtp.user._id) {
    await dtp.app.connect();
  }

  dtp.log.debug('load', 'dispatching load event');
  window.dispatchEvent(new Event('dtp-load'));
});

document.addEventListener('socketConnected', async ( ) => {
  if (dtp.room) {
    dtp.app.socket.joinChannel(dtp.room._id);
    if (dtp.user && (dtp.user._id === dtp.room.owner._id)) {
      dtp.app.socket.joinChannel(`broadcast:${dtp.room._id}`);
    }
  }
});