/* tslint:disable:no-console */
/**
 * @module SSBIntegration
 */ /** for typedoc */

const { ipcRenderer, crashReporter, webFrame } = require('electron');

function receiveMessage(event) {
  // Yep, we're parsing it again
  if (!event.isTrusted) {
    return;
  }

  const { hostname, protocol, port } = new URL(window.location.origin);
  const hostRgx = /(\.|^)slack\.(eu|com)$/;

  const isOriginMatch = hostRgx.test(hostname) &&
    protocol === 'https:' &&
    (port === '' || port === '443');
  const isDataExpected = !!event.data && !!event.data.type;

  if (!isOriginMatch || !isDataExpected) return;

  try {
    const { type, args } = event.data;
    switch (type) {
      case 'didFinishLoading':
        ipcRenderer.send('SLACK_DID_FINISH_LOADING');
        break;
      case 'didSignIn':
        ipcRenderer.send('SLACK_DID_SIGN_IN', ...args);
        break;
    }
  } catch (e) {
    console.log(e);
  }
}
window.addEventListener('message', receiveMessage, false);

// Assign preload script proxies to preload script's ipc
const preloadTemplate = `
window.desktop = window.winssb = {
  app: { didFinishLoading: () => { window.postMessage({ type: 'didFinishLoading' }, window.location.origin) } },
  teams: { didSignIn: (...args) => { window.postMessage({ type: 'didSignIn', args: args }, window.location.origin) } }
};`;

webFrame.executeJavaScript(preloadTemplate);

const allowedMetadata = ['loadSettings', 'crashReporterOpts'];
const assignMetadata = () => {
  try {
    const metadataArgs = process.argv.find((x) => x.includes('slack_preload_metadata_arguments')) || '{}';
    const metadataJson = JSON.parse(metadataArgs);
    Object.keys(metadataJson)
      .filter((key) => allowedMetadata.includes(key))
      .forEach((key) => window[key] = metadataJson[key]);
  } catch (e) {
    console.log(e); //tslint:disable-line:no-console
  }
};
assignMetadata();

if (window.crashReporterOpts) {
  try {
    crashReporter.start(window.crashReporterOpts);
  } catch (error) {
    //tslint:disable-next-line:no-console
    console.error('CrashReporter: Unable to start crash report service', { error });
  }
}
