'use strict';

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.completionRequest = exports.pick = undefined;
exports.formChangeObject = formChangeObject;
exports.codeCompleteObservable = codeCompleteObservable;
exports.codeComplete = codeComplete;

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

var _Rx2 = _interopRequireDefault(_Rx);

var _messaging = require('../../../kernel/messaging');

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

// Hint picker
const pick = exports.pick = (cm, handle) => handle.pick();

function formChangeObject(cm, change) {
  return {
    cm,
    change
  };
}

function codeCompleteObservable(channels, editor, message) {
  const completion$ = channels.shell.childOf(message).ofMessageType('complete_reply').pluck('content').first().map(results => ({
    list: results.matches,
    from: editor.posFromIndex(results.cursor_start),
    to: editor.posFromIndex(results.cursor_end)
  })).timeout(2000); // 4s

  // On subscription, send the message
  return _Rx2.default.Observable.create(observer => {
    const subscription = completion$.subscribe(observer);
    channels.shell.next(message);
    return subscription;
  });
}

const completionRequest = exports.completionRequest = (code, cursorPos) => (0, _messaging.createMessage)('complete_request', {
  content: {
    code,
    cursor_pos: cursorPos
  }
});

function codeComplete(channels, editor) {
  const cursor = editor.getCursor();
  const cursorPos = editor.indexFromPos(cursor);
  const code = editor.getValue();

  const message = completionRequest(code, cursorPos);

  return codeCompleteObservable(channels, editor, message);
}