'use strict';

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

var _path = require('path');

var _path2 = _interopRequireDefault(_path);

var _xss = require('xss');

var _xss2 = _interopRequireDefault(_xss);

var _package = require('../../../package');

var _package2 = _interopRequireDefault(_package);

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

var _editor = require('../controllers/editor');

var _abeLocale = require('../helpers/abe-locale');

var _abeLocale2 = _interopRequireDefault(_abeLocale);

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

function renderAbeAdmin(EditorVariables, obj, filePath) {
  var manager = {};

  manager.home = {
    files: [] //Manager.instance.getList()
  };

  manager.list = _cli.Manager.instance.getStructureAndTemplates();
  manager.editConfig = EditorVariables.express.req.app.get('config');
  manager.config = JSON.stringify(_cli.config);

  var _hasBlock = obj ? obj.hasBlock : false;
  var _hasSingleBlock = obj ? obj.hasSingleBlock : false;
  var _preview = filePath ? '/abe/page/' + EditorVariables.express.req.params[0] + ('?filePath=' + EditorVariables.express.req.query.filePath) : false;
  var _form = obj ? obj.form : false;
  var _json = obj ? obj.json : false;
  var _filePath = filePath ? filePath : false;
  if (_filePath) {
    _filePath = '/' + _filePath.replace(/^\/+/, '');
  }

  var pageHtml = '';
  if (typeof _json !== 'undefined' && _json !== null && typeof _json.abe_meta !== 'undefined' && _json.abe_meta !== null) {

    var text = _cli.cmsTemplates.template.getTemplate(_json.abe_meta.template, _json);
    var page = new _cli.Page(_json.abe_meta.template, text, _json, false);
    pageHtml = page.html.replace(/"/g, '"').replace(/'/g, '\'').replace(/<!--/g, '<ABE!--').replace(/-->/g, '--ABE>');
  }

  var editorWidth = '33%';
  EditorVariables.express.req.headers && EditorVariables.express.req.headers.cookie && EditorVariables.express.req.headers.cookie.split(';').forEach(function (cookie) {
    var parts = cookie.match(/(.*?)=(.*)$/);
    if (parts[1] === 'editorWidth') editorWidth = parts[2];
  });

  EditorVariables.pageHtml = pageHtml;
  EditorVariables.test = JSON.stringify(_abeLocale2.default);
  EditorVariables.text = _abeLocale2.default;
  EditorVariables.preview = _preview;
  EditorVariables.hasSingleBlock = _hasSingleBlock;
  EditorVariables.hasBlock = _hasBlock;
  EditorVariables.form = _form;
  EditorVariables.json = _json;
  EditorVariables.manager = manager;
  //  EditorVariables.nonce = '\'nonce-' + EditorVariables.express.res.locals.nonce + '\''
  EditorVariables.editorWidth = editorWidth;

  if (_json != null && _json.abe_meta) {
    EditorVariables.workflows = _cli.User.utils.getUserWorkflow(_json.abe_meta.status);
  }

  EditorVariables = _cli.abeExtend.hooks.instance.trigger('afterVariables', EditorVariables);

  if (filePath != null && filePath.indexOf('.json') > -1) {
    EditorVariables.express.res.set('Content-Type', 'application/json');
    EditorVariables.express.res.send(JSON.stringify(_json));
  } else {
    EditorVariables.express.res.render(_cli.config.abeEngine, EditorVariables);
  }
}

var route = function route(req, res, next) {
  var filePath = req.originalUrl.replace('/abe/editor', '');
  if (filePath === '' || filePath === '/') {
    filePath = null;
  }

  if (filePath != null) {
    var testXSS = (0, _xss2.default)(filePath, {
      whiteList: [],
      stripIgnoreTag: true
    });
    if (testXSS !== filePath) {
      filePath = testXSS;
    }
  }

  _cli.abeExtend.hooks.instance.trigger('beforeRoute', req, res, next);
  if (typeof res._header !== 'undefined' && res._header !== null) return;

  var isHome = true;
  var jsonPath = null;
  var linkPath = null;
  var template = null;
  var fileName = null;
  var folderPath = null;

  var EditorVariables = {
    user: res.user,
    slugs: _cli.Manager.instance.getSlugs(),
    express: {
      res: res,
      req: req
    },
    filename: fileName,
    folderPath: folderPath,
    abeUrl: '/abe/editor/',
    isHome: isHome,
    config: _cli.config,
    Locales: _cli.coreUtils.locales.instance.i18n,
    abeVersion: _package2.default.version
  };

  var p = new Promise(function (resolve) {

    if (filePath != null) {
      fileName = _path2.default.basename(filePath);
      folderPath = _path2.default.dirname(filePath);

      EditorVariables.isHome = false;
      var filePathTest = _cli.cmsData.revision.getDocumentRevision(filePath);
      if (typeof filePathTest !== 'undefined' && filePathTest !== null) {
        jsonPath = filePathTest.path;
        linkPath = filePathTest.abe_meta.link;
        template = filePathTest.abe_meta.template;
      }

      if (jsonPath === null || !_cli.coreUtils.file.exist(jsonPath)) {
        res.redirect('/abe/editor');
        return;
      }

      var json = {};
      if (_cli.coreUtils.file.exist(jsonPath)) {
        json = _cli.cmsData.file.get(jsonPath, 'utf8');
      }
      var text = _cli.cmsTemplates.template.getTemplate(template, json);
      (0, _editor.editor)(text, json, linkPath).then(function (result) {
        resolve(result);
      }).catch(function (e) {
        console.error(e);
      });
    } else {
      resolve({
        json: {},
        manager: {}
      });
    }
  }).catch(function (e) {
    console.error(e); // "oh, no!"
  });

  p.then(function (obj) {
    var precontrib = _cli.Manager.instance.getPrecontribution();
    (0, _editor.editor)(precontrib.template, obj.json, '', true).then(function (resultPrecontrib) {
      EditorVariables.resultPrecontrib = resultPrecontrib;
      renderAbeAdmin(EditorVariables, obj, filePath, isHome, template);
    }).catch(function (e) {
      console.error(e);
    });
  }).catch(function (e) {
    console.log('error', e);
  });
};

exports.default = route;