'use strict';

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.createSplashSubscriber = createSplashSubscriber;

var _electron = require('electron');

var _path = require('path');

var _Rx = require('rxjs/Rx');

var _Rx2 = _interopRequireDefault(_Rx);

var _launch = require('./launch');

var _menu = require('./menu');

var _prepareEnv = require('./prepare-env');

var _prepareEnv2 = _interopRequireDefault(_prepareEnv);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

const path = require('path');

const log = require('electron-log');

const kernelspecs = require('kernelspecs');

const version = require('../../package.json').version;

log.info('args', process.argv);

const sliceAt = process.argv[0].match('nteract') ? 1 : 2;

const argv = require('yargs').version(version).parse(process.argv.slice(sliceAt));

const notebooks = argv._.filter(Boolean).filter(x => /^(?!-psn)/.test(x)) // Ignore strangeness on OS X first launch
// see #805
.filter(x => x !== '.'); // Ignore the `electron .`
// TODO: Consider opening something for directories

_electron.ipcMain.on('new-kernel', (event, newKernel) => {
  (0, _launch.launchNewNotebook)(newKernel);
});

_electron.ipcMain.on('open-notebook', (event, filename) => {
  (0, _launch.launch)(path.resolve(filename));
});

const electronReady$ = _Rx2.default.Observable.fromEvent(_electron.app, 'ready');

const fullAppReady$ = _Rx2.default.Observable.zip(electronReady$, _prepareEnv2.default).first();

const kernelSpecsPromise = _prepareEnv2.default.toPromise().then(() => kernelspecs.findAll());

/**
 * Creates an Rx.Subscriber that will create a splash page onNext and close the
 * splash page onComplete.
 * @return {Rx.Subscriber} Splash Window subscriber
 */
function createSplashSubscriber() {
  let win;

  return _Rx2.default.Subscriber.create(() => {
    win = new _electron.BrowserWindow({
      width: 900,
      height: 400,
      title: 'loading',
      frame: false
    });

    const index = path.join(__dirname, '..', '..', 'static', 'splash.html');
    win.loadURL(`file://${ index }`);
    win.show();
  }, null, () => {
    // Close the splash page when completed
    if (win) {
      win.close();
    }
  });
}

const appAndKernelSpecsReady = _Rx2.default.Observable.zip(fullAppReady$, kernelSpecsPromise);

const splashSubscription = electronReady$
// TODO: Take until first window is shown
.takeUntil(appAndKernelSpecsReady).subscribe(createSplashSubscriber());

function closeAppOnNonDarwin() {
  // On OS X, we want to keep the app and menu bar active
  if (process.platform !== 'darwin') {
    _electron.app.quit();
  }
}
const windowAllClosed = _Rx2.default.Observable.fromEvent(_electron.app, 'window-all-closed');
const windowClosedSubscription = windowAllClosed.skipUntil(appAndKernelSpecsReady).subscribe(closeAppOnNonDarwin);

const openFile$ = _Rx2.default.Observable.fromEvent(_electron.app, 'open-file', (event, filename) => ({ event, filename }));

function openFileFromEvent({ event, filename }) {
  event.preventDefault();
  (0, _launch.launch)(path.resolve(filename));
}

// Since we can't launch until app is ready
// and OS X will send the open-file events early,
// buffer those that come early.
openFile$.buffer(fullAppReady$) // Form an array of open-file events from before app-ready
.first() // Should only be the first
.subscribe(buffer => {
  // Now we can choose whether to open the default notebook
  // based on if arguments went through argv or through open-file events
  if (notebooks.length <= 0 && buffer.length <= 0) {
    log.info('launching an empty notebook by default');
    kernelSpecsPromise.then(specs => {
      const defaultKernel = 'python3';
      let kernel = defaultKernel;

      if ('python3' in specs) {
        kernel = 'python3';
      } else if ('python2' in specs) {
        kernel = 'python2';
      } else {
        const specList = Object.keys(specs);
        specList.sort();
        kernel = specList[0];
      }

      (0, _launch.launchNewNotebook)(kernel);
    });
  } else {
    notebooks.forEach(f => {
      try {
        (0, _launch.launch)((0, _path.resolve)(f));
      } catch (e) {
        log.error(e);
        console.error(e);
      }
    });
  }
  buffer.forEach(openFileFromEvent);
});

// All open file events after app is ready
openFile$.skipUntil(fullAppReady$).subscribe(openFileFromEvent);

fullAppReady$.subscribe(() => {
  kernelSpecsPromise.then(kernelSpecs => {
    if (Object.keys(kernelSpecs).length !== 0) {
      // Get the default menu first
      _electron.Menu.setApplicationMenu(_menu.defaultMenu);
      // Let the kernels/languages come in after
      (0, _menu.loadFullMenu)().then(menu => _electron.Menu.setApplicationMenu(menu));
    } else {
      _electron.dialog.showMessageBox({
        type: 'warning',
        title: 'No Kernels Installed',
        buttons: [],
        message: 'No kernels are installed on your system.',
        detail: 'No kernels are installed on your system so you will not be ' + 'able to execute code cells in any language. You can read about ' + 'installing kernels at ' + 'https://ipython.readthedocs.io/en/latest/install/kernel_install.html'
      }, index => {
        if (index === 0) {
          _electron.app.quit();
        }
      });
    }
  }).catch(err => {
    _electron.dialog.showMessageBox({
      type: 'error',
      title: 'No Kernels Installed',
      buttons: [],
      message: 'No kernels are installed on your system.',
      detail: 'No kernels are installed on your system so you will not be ' + 'able to execute code cells in any language. You can read about ' + 'installing kernels at ' + 'https://ipython.readthedocs.io/en/latest/install/kernel_install.html' + `\nFull error: ${ err.message }`
    }, index => {
      if (index === 0) {
        _electron.app.quit();
      }
    });
  });
});