'use strict';

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

var _path = require('path');

var _path2 = _interopRequireDefault(_path);

var _fsExtra = require('fs-extra');

var _fsExtra2 = _interopRequireDefault(_fsExtra);

var _handlebars = require('handlebars');

var _handlebars2 = _interopRequireDefault(_handlebars);

var _cli = require('../../cli');

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

var route = function route(router, req, res, next) {
  _cli.abeExtend.hooks.instance.trigger('beforeRoute', req, res, next);
  var routes = router.stack;
  var urls = [];
  var html = '';

  Array.prototype.forEach.call(routes, function (route) {
    urls.push({
      url: route.route.path,
      method: Object.keys(route.route.methods)[0].toUpperCase(),
      regex: route.route.path.replace(/\*$/, '') + '.*'
    });
  });

  var page = _path2.default.join(__dirname + '/../views/list-url.html');
  if (_cli.coreUtils.file.exist(page)) {
    html = _fsExtra2.default.readFileSync(page, 'utf8');
  }

  var workflowUrl = {};
  Array.prototype.forEach.call(_cli.config.users.workflow, function (flow) {
    workflowUrl[flow] = [{ url: '/abe/operations/edit/' + flow, action: 'edit', workflow: flow }, { url: '/abe/operations/delete/' + flow, action: 'delete', workflow: flow }];
  });
  var template = _handlebars2.default.compile(html, { noEscape: true });
  var tmp = template({
    urls: urls,
    user: res.user,
    config: JSON.stringify(_cli.config),
    roles: _cli.config.users.roles,
    workflow: _cli.config.users.workflow,
    workflowUrl: workflowUrl
  });

  res.cookie('csrf-token', res.locals.csrfToken);
  return res.send(tmp);
};

exports.default = route;