'use strict';

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.tildify = tildify;
exports.setTitleFromAttributes = setTitleFromAttributes;
exports.createTitleFeed = createTitleFeed;
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 setTitleFromAttributes(attributes) {
  const filename = tildify(attributes.fullpath);
  const { executionState } = attributes;

  const win = getCurrentWindow();
  // TODO: Investigate if setRepresentedFilename() is a no-op on non-OS X
  if (filename && win.setRepresentedFilename) {
    win.setRepresentedFilename(attributes.fullpath);
    win.setDocumentEdited(attributes.modified);
  }
  const title = `${ filename } - ${ executionState }`;
  win.setTitle(title);
}

function createTitleFeed(state$) {
  const modified$ = state$.map(state => state.document.get('notebook')).scan((prev, notebook) => ({
    modified: prev.notebook === notebook,
    notebook
  }), {}).pluck('modified');

  const fullpath$ = state$.map(state => state.metadata.get('filename') || 'Untitled');

  const executionState$ = state$.map(state => state.app.get('executionState')).debounceTime(200);

  return _Rx2.default.Observable.combineLatest(modified$, fullpath$, executionState$, (modified, fullpath, executionState) => ({ modified, fullpath, executionState })).distinctUntilChanged().switchMap(i => _Rx2.default.Observable.of(i));
}

function initNativeHandlers(store) {
  const state$ = _Rx2.default.Observable.from(store);
  return createTitleFeed(state$).subscribe(setTitleFromAttributes, err => console.error(err));
}