'use strict';

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

var _electron = require('electron');

var _homeDir = require('home-dir');

var _homeDir2 = _interopRequireDefault(_homeDir);

var _path = require('path');

var _path2 = _interopRequireDefault(_path);

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

var _Rx2 = _interopRequireDefault(_Rx);

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

const HOME = (0, _homeDir2.default)();
const { getCurrentWindow } = _electron.remote;

/**
 * Turn a path like /Users/n/mine.ipynb to ~/mine.ipynb
 * @param  {string} p the full path to a file
 * @return {string}   tildified path
 */
function tildify(p) {
  if (!p) {
    return '';
  }
  const s = _path2.default.normalize(p) + _path2.default.sep;
  return (s.indexOf(HOME) === 0 ? s.replace(HOME + _path2.default.sep, `~${ _path2.default.sep }`) : s).slice(0, -1);
}

function titleFromState(state) {
  const modified = state.app.get('modified');
  const executionState = state.app.get('executionState');
  const filename = tildify(state.metadata.get('filename')) || 'Untitled';
  const displayName = state.document.getIn(['notebook', 'metadata', 'kernelspec', 'display_name'], '...');

  return {
    title: `${ filename } - ${ displayName } - ${ executionState } ${ modified ? '*' : '' }`,
    path: filename
  };
}

function initNativeHandlers(store) {
  _Rx2.default.Observable.from(store).map(titleFromState).distinctUntilChanged().debounceTime(200).subscribe(res => {
    const win = getCurrentWindow();
    // TODO: Investigate if setRepresentedFilename() is a no-op on non-OS X
    if (res.path && win.setRepresentedFilename) {
      // TODO: this needs to be the full path to the file
      win.setRepresentedFilename(res.path);
    }
    win.setTitle(res.title);
  });
}