/* eslint-disable no-unused-vars */
const { ipcRenderer } = require('electron');

/**
 * Name doesn't really matter here, because we re-assign it to the vizality.native global
 * on startup later and delete this.
 */
window.VizalityNative = {
  app: {
    /**
     * Opens Chrome Developer Tools for the current window.
     * @param {object} options Options to pass to Electron
     * @param {boolean} externalWindow Whether the Chrome Developer Tools should be opened in an external window or not
     */
    openDevTools (options, externalWindow) {
      return ipcRenderer.invoke('VIZALITY_OPEN_DEVTOOLS', options, externalWindow);
    },

    /**
     * Closes Chrome Developer Tools for the current window.
     */
    closeDevTools () {
      return ipcRenderer.invoke('VIZALITY_CLOSE_DEVTOOLS');
    },

    /**
     * Clears Chromium's cache.
     * @returns {Promise<void>}
     */
    clearCache () {
      return ipcRenderer.invoke('VIZALITY_CLEAR_CACHE');
    },

    openBrowserWindow (options) {
      throw new Error('Not implemented');
    },

    /**
     * Gets the path browsing history.
     * @returns {Promise<Array<string|null>>}
     */
    getHistory () {
      return ipcRenderer.invoke('VIZALITY_GET_HISTORY');
    }
  },

  /**
   * Compiles a Sass file.
   * @param {string} file File path to compile
   * @returns {Promise<void>}
   */
  _compileSass (file) {
    return ipcRenderer.invoke('VIZALITY_COMPILE_SASS', file);
  }
};

/**
 * A list of node modules to be whitelisted for use in Chrome Developer Tools console.
 */
const WHITELISTED_MODULES = [
  'crypto',
  'lodash',
  'moment',
  'react',
  'react-dom',
  'react-router',
  'react-spring',
  'framer-motion'
];

/**
 * Make sure window exists and it's not the splash screen, then check if the module
 * is whitelisted, and if it's not, throw an error.
 */
if (window && !window.__SPLASH__) {
  window.require = module => {
    try {
      if (WHITELISTED_MODULES.includes(module) || module.startsWith('@vizality') || module.startsWith('@discord')) {
        return require(module);
      }
      throw new Error(`Node module "${module.toString()}" is not whitelisted and cannot be used in this scope.`);
    } catch (err) {
      return require('@vizality/util/logger').error({ labels: [ 'Vizality', 'Core' ], message: err });
    }
  };
}
