
const { ipcMain } = require('electron');
const electronLog = require('electron-log');
const { autoUpdater } = require('electron-updater');

class ElectronLogBridge {
  constructor(desktop) {
    this.desktop = desktop;

    // Set up logging...
    // electronLog.transports.console.format = '%c{h}:{i}:{s}.{ms}%c <{level}> {text}';

    electronLog.transports.console.level = this.desktop.appDev ? 'info' : 'debug';
    electronLog.transports.file.format = '%c{h}:{i}:{s}.{ms}%c <{level}> {text}';
    electronLog.transports.file.level = 'debug';
    autoUpdater.logger = electronLog;

    ipcMain.on('log', (event, ...args) => {
      const level = this.normalizeLogLevel(args.shift());
      const parts = args.shift();
      this.writeLogEntry(level, ...parts);
    });
  }

  normalizeLogLevel = (l) => {
    if (l === 1 || l === 'verbose') return 'VRB';
    if (l === 2 || l === 'debug') return 'DBG';
    if (l === 4 || l === 'warn') return 'WRN';
    if (l === 5 || l === 'error') return 'ERR';
    return 'INF';
  }

  writeLogEntry = (level, ...parts) => {
    if (level === 'DBG') {
      electronLog.debug(...parts);
    } else if (level === 'VRB') {
      electronLog.verbose(...parts);
    } else if (level === 'WRN') {
      electronLog.warn(...parts);
    } else if (level === 'ERR') {
      electronLog.error(...parts);
    } else {
      electronLog.info(...parts);
    }
  }

  verbose = (...args) => { return this.writeLogEntry('VRB', ...args); }
  debug = (...args) => { return this.writeLogEntry('DBG', ...args); }
  info = (...args) => { return this.writeLogEntry('INF', ...args); }
  warn = (...args) => { return this.writeLogEntry('WRN', ...args); }
  error = (...args) => { return this.writeLogEntry('ERR', ...args); }
}

module.exports = ElectronLogBridge;

