'use strict';

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

var _path = require('path');

var _path2 = _interopRequireDefault(_path);

var _extend = require('extend');

var _extend2 = _interopRequireDefault(_extend);

var _ = require('../../');

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

var duplicate = function duplicate(oldPostUrl, template, newPath, name, req) {
  var isUpdate = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : false;

  var p = new Promise(function (resolve, reject) {
    _.abeExtend.hooks.instance.trigger('beforeDuplicate', oldPostUrl, template, newPath, name, req, isUpdate);

    var json = {};
    var revisions = [];
    var newPostUrl = _path2.default.posix.join(newPath, _.coreUtils.slug.clean(name));
    if (oldPostUrl != null) {
      var files = _.Manager.instance.getList();
      var oldPostDataPath = _path2.default.join(_.config.root, _.config.data.url, oldPostUrl.replace('.' + _.config.files.templates.extension, '.json'));
      var posts = [];
      posts = _.coreUtils.array.filter(files, 'path', oldPostDataPath);

      if (posts.length > 0 && posts[0].revisions != null) {
        revisions = posts[0].revisions;
        if (revisions != null && revisions[0] != null) {
          json = _.cmsData.file.get(revisions[0].path);
          json = (0, _extend2.default)(true, json, req.body);

          delete json.abe_meta;
        }
      }
    }

    _.abeExtend.hooks.instance.trigger('afterDuplicate', json, oldPostUrl, template, newPath, name, req, isUpdate);

    var pCreate = _.cmsOperations.create(template, newPath, name, req, json, isUpdate ? false : true);
    pCreate.then(function (resSave) {
      if (isUpdate && oldPostUrl !== _path2.default.posix.join('/', newPostUrl)) {
        _.abeExtend.hooks.instance.trigger('beforeUpdate', json, oldPostUrl, template, newPath, name, req, isUpdate);
        _.cmsOperations.remove.remove(oldPostUrl);
      }
      resolve(resSave);
    }, function () {
      reject();
    }).catch(function (e) {
      console.error('[ERROR] abe-duplicate.js', e);
      reject();
    });
  });

  return p;
};

exports.default = duplicate;