const { relative, join, dirname, posix, sep, resolve } = require('path');
const { existsSync, promises: { readFile } } = require('fs');
const { ipcMain, BrowserWindow } = require('electron');
const { renderSync } = require('sass');

/**
 *
 * @param {*} evt
 * @param {*} opts
 * @param {*} externalWindow
 */
function openDevTools (evt, opts, externalWindow) {
  evt.sender.openDevTools(opts);
  if (externalWindow) {
    let devToolsWindow = new BrowserWindow({
      webContents: evt.sender.devToolsWebContents
    });
    devToolsWindow.on('ready-to-show', () => devToolsWindow.show());
    devToolsWindow.on('close', () => {
      evt.sender.closeDevTools();
      devToolsWindow = null;
    });
  }
}

/**
 *
 * @param {*} evt
 */
function closeDevTools (evt) {
  evt.sender.closeDevTools();
}

/**
 *
 * @param {*} evt
 * @returns
 */
function clearCache (evt) {
  return new Promise(resolve => {
    evt.sender.session.clearCache(() => resolve(null));
  });
}

/**
 *
 * @param {*} evt
 * @returns
 */
function getHistory (evt) {
  return evt.sender.history;
}

/**
 *
 * @param {*} _
 * @param {*} file
 * @returns
 */
function compileSass (_, file) {
  return new Promise((res, reject) => {
    readFile(file, 'utf8').then(rawScss => {
      try {
        const relativePath = relative(file, join(__dirname, '..', 'renderer', 'src', 'styles', 'utils'));
        const absolutePath = resolve(join(file, relativePath));
        const fixedScss = rawScss.replace('@vizality', absolutePath.split(sep).join(posix.sep));
        const result = renderSync({
          data: fixedScss,
          importer: (url, prev) => {
            if (url === '@vizality') {
              url = url.replace('@vizality', absolutePath.split(sep).join(posix.sep));
            }
            url = url.replace('file:///', '');
            if (existsSync(url)) {
              return {
                file: url
              };
            }
            const prevFile =
              prev === 'stdin'
                ? file
                : prev.replace(/https?:\/\/(?:[a-z]+\.)?discord(?:app)?\.com/i, '');
            return {
              file: join(dirname(decodeURI(prevFile)), url).split(sep).join(posix.sep)
            };
          }
        });
        if (result) {
          return res(result.css.toString());
        }
      } catch (err) {
        return reject(err);
      }
    });
  });
}

ipcMain.on('VIZALITY_GET_PRELOAD', evt => evt.returnValue = evt.sender._preload);
ipcMain.handle('VIZALITY_GET_HISTORY', getHistory);
ipcMain.handle('VIZALITY_OPEN_DEVTOOLS', openDevTools);
ipcMain.handle('VIZALITY_CLOSE_DEVTOOLS', closeDevTools);
ipcMain.handle('VIZALITY_CLEAR_CACHE', clearCache);
ipcMain.handle('VIZALITY_WINDOW_IS_MAXIMIZED', evt => BrowserWindow.fromWebContents(evt.sender).isMaximized());
ipcMain.handle('VIZALITY_COMPILE_SASS', compileSass);
