'use strict';

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

var _path = require('path');

var _path2 = _interopRequireDefault(_path);

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

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

var create = function create(template, pathCreate, name, req) {
  var forceJson = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : {};
  var duplicate = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : false;

  var p = new Promise(function (resolve) {
    _.abeExtend.hooks.instance.trigger('beforeCreate', template, pathCreate, name, req, forceJson);

    var postUrl = _path2.default.join('/', pathCreate, name);
    postUrl = _.coreUtils.slug.clean(postUrl);

    var json = forceJson ? forceJson : {};

    json = _.cmsData.metas.create(json, template, postUrl);

    if (duplicate) {
      if (json.abe_meta.publish != null) {
        delete json.abe_meta.publish;
      }
      var templateText = _.cmsTemplates.template.getTemplate(template);
      json = _.cmsData.values.removeDuplicate(templateText, json);
    }

    var resHook = _.abeExtend.hooks.instance.trigger('beforeFirstSave', postUrl, req.body, json);
    postUrl = resHook.postUrl;
    json = resHook.json;
    var p2 = _.cmsOperations.post.draft(postUrl, json, 'draft');
    p2.then(function (result) {
      _.abeExtend.hooks.instance.trigger('afterCreate', result);
      resolve(result.json);
    }).catch(function (e) {
      console.error('[ERROR] create.js', e);
    });
  }).catch(function (e) {
    console.error(e);
  });

  return p;
};

exports.default = create;