'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 _cli = require('../../cli');

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

var middleware = function middleware(req, res, next) {
  if (req.originalUrl.indexOf('/abe/') > -1) {
    return next();
  }

  if (req.originalUrl === '' || req.originalUrl === '/' || req.originalUrl.indexOf('.') === -1) {
    var pathWebsite = _path2.default.join(_cli.config.root, _cli.config.publish.url, req.originalUrl);
    try {
      var directory = _fsExtra2.default.lstatSync(pathWebsite);
      if (!directory.isDirectory()) {
        return next();
      }
    } catch (e) {
      return next();
    }
    var files = _cli.coreUtils.file.getFilesSync(pathWebsite, false);
    var folders = _cli.coreUtils.file.getFoldersSync(pathWebsite, false);
    var html = '<ul>';
    html += '<li><a href="/abe/editor">abe</abe></li>';
    html += '<br />';
    if (req.originalUrl !== '/' && req.originalUrl !== '') {
      var parent = req.originalUrl.replace(/\/$/, '').split('/');
      parent.pop();
      parent = parent.join('/') + '/';
      html += '<li><a href="' + parent + '">../</abe></li>';
    }

    if (typeof folders !== 'undefined' && folders !== null) {
      Array.prototype.forEach.call(folders, function (folder) {
        var url = folder.path.replace(_path2.default.join(_cli.config.root, _cli.config.publish.url), '');
        html += '<li><a href="' + url + '">/' + _path2.default.basename(folder.path) + '</a></li>';
      });
    }
    if (typeof files !== 'undefined' && files !== null) {
      Array.prototype.forEach.call(files, function (file) {
        var url = file.replace(_path2.default.join(_cli.config.root, _cli.config.publish.url), '');
        html += '<li><a href="' + url + '">' + _path2.default.basename(file) + '</a></li>';
      });
    }
    html += '</ul>';

    res.set('Content-Type', 'text/html');
    return res.send(html);
  } else if (req.originalUrl.indexOf('.' + _cli.config.files.templates.extension) > -1) {

    html = '';

    var page = _path2.default.join(_cli.config.root, _cli.config.publish.url, req.originalUrl);
    if (_cli.coreUtils.file.exist(page)) {
      html = _fsExtra2.default.readFileSync(page, 'utf8');
    } else {
      return next();
    }

    html = _cli.abeExtend.hooks.instance.trigger('beforePreview', html, req, res, next);
    res.set('Content-Type', 'text/html');
    return res.send(html);
  } else {
    return next();
  }
};

exports.default = middleware;