'use strict';

var _ms = require('ms');

var _ms2 = _interopRequireDefault(_ms);

var _helpers = require('../database/helpers');

var _helpers2 = _interopRequireDefault(_helpers);

var _moment = require('moment');

var _moment2 = _interopRequireDefault(_moment);

var _lodash = require('lodash');

var _lodash2 = _interopRequireDefault(_lodash);

var _bluebird = require('bluebird');

var _bluebird2 = _interopRequireDefault(_bluebird);

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

function _asyncToGenerator(fn) { return function () { var gen = fn.apply(this, arguments); return new _bluebird2.default(function (resolve, reject) { function step(key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { return _bluebird2.default.resolve(value).then(function (value) { step("next", value); }, function (err) { step("throw", err); }); } } return step("next"); }); }; }

module.exports = ({ db, botfile, middlewares }) => {
  let intervalRef = null;

  const defaultJanitorInterval = (0, _ms2.default)(_lodash2.default.get(botfile, 'dialogs.janitorInterval') || '30s');
  const defaultTimeout = (0, _ms2.default)(_lodash2.default.get(botfile, 'dialogs.timeoutInterval') || '15m');

  const checkStaleSessions = (() => {
    var _ref = _asyncToGenerator(function* () {
      const knex = yield db.get();

      const timedOutCondition = (0, _helpers2.default)(knex).date.isBefore('active_on', (0, _moment2.default)().subtract(defaultTimeout, 'milliseconds'));

      const sessions = yield knex('dialog_sessions').where(timedOutCondition).andWhereRaw(`not "id" like '%\\_\\_\\_%' escape '\\'`) // Exclude substates
      .limit(250).then();

      return _bluebird2.default.map(sessions, function (session) {
        let platform = 'botpress';
        const props = {};

        if (session.id.includes(':')) {
          const chunks = session.id.split(':');
          platform = _lodash2.default.head(chunks);
          const userId = _lodash2.default.tail(chunks).join(':');
          props.user = { id: userId };
        }

        return middlewares.sendIncoming(_lodash2.default.merge({
          platform: platform,
          type: 'bp_dialog_timeout',
          raw: { sessionId: session.id },
          text: session.id,
          sessionId: session.id
        }, props));
      });
    });

    return function checkStaleSessions() {
      return _ref.apply(this, arguments);
    };
  })();

  const run = (() => {
    var _ref2 = _asyncToGenerator(function* () {
      yield checkStaleSessions();
    });

    return function run() {
      return _ref2.apply(this, arguments);
    };
  })();

  const uninstall = () => {
    if (intervalRef) {
      clearInterval(intervalRef);
      intervalRef = null;
    }
  };

  const install = () => {
    const randomMs = Math.random() * 5000;

    if (intervalRef) {
      uninstall();
    }

    intervalRef = setInterval(run, defaultJanitorInterval + randomMs);
  };

  return { install, uninstall, runOnce: run };
};
//# sourceMappingURL=janitor.js.map