'use strict';

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.draft = draft;
exports.publish = publish;
exports.unpublish = unpublish;
exports.submit = submit;
exports.reject = reject;

var _path = require('path');

var _path2 = _interopRequireDefault(_path);

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

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

function draft(filePath, json) {
  var workflow = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 'draft';

  var p = new Promise(function (resolve) {
    _.abeExtend.hooks.instance.trigger('beforeDraft', json, filePath);

    var revisionPath = _path2.default.join(_.config.root, _.config.data.url, filePath.replace('.' + _.config.files.templates.extension, '.json'));
    revisionPath = _.coreUtils.file.addDateIsoToRevisionPath(revisionPath, workflow);
    var date = _.coreUtils.file.getDate(revisionPath);
    _.cmsData.metas.add(json, workflow, date);

    var template = _.cmsTemplates.template.getTemplate(json.abe_meta.template, json);

    _.cmsData.source.getDataList(_path2.default.dirname(json.abe_meta.link), template, json).then(function () {

      json['abe_meta'].complete = _.cmsData.utils.getPercentOfRequiredTagsFilled(template, json);

      // var page = new Page(json.abe_meta.template, template, json, true)
      var result;
      if (!_.cmsOperations.save.saveJson(revisionPath, json)) {
        result = {
          success: 0,
          error: 'cannot json save file'
        };
      } else {
        _.Manager.instance.updatePostInList(revisionPath);
        result = {
          success: 1,
          json: json
        };
      }
      resolve(result);
    });
  });

  return p;
}

function publish(filePath, json) {
  var p = new Promise(function (resolve) {
    _.abeExtend.hooks.instance.trigger('beforePublish', json, filePath);

    var revisionPath = _path2.default.join(_.config.root, _.config.data.url, filePath.replace('.' + _.config.files.templates.extension, '.json'));
    var postPath = _path2.default.join(_.config.root, _.config.publish.url, filePath);
    // revisionPath = coreUtils.file.addDateIsoToRevisionPath(revisionPath, workflow)
    _.cmsData.metas.add(json, 'publish');

    var template = _.cmsTemplates.template.getTemplate(json.abe_meta.template, json);

    _.cmsData.source.getDataList(_path2.default.dirname(json.abe_meta.link), template, json).then(function () {
      json['abe_meta'].complete = _.cmsData.utils.getPercentOfRequiredTagsFilled(template, json);

      var page = new _.Page(json.abe_meta.template, template, json, true);

      var result;
      if (!_.cmsOperations.save.saveHtml(postPath, page.html)) {
        result = {
          success: 0,
          error: 'cannot save html file'
        };
      } else {
        if (!_.cmsOperations.save.saveJson(revisionPath, json)) {
          result = {
            success: 0,
            error: 'cannot save json file'
          };
        } else {
          _.Manager.instance.updatePostInList(revisionPath);
          _.abeExtend.hooks.instance.trigger('afterPublish', json, filePath);
          result = {
            success: 1,
            json: json
          };
        }
      }
      resolve(result);
    });
  });

  return p;
}

function unpublish(filePath) {
  _.abeExtend.hooks.instance.trigger('beforeUnpublish', filePath);

  var p = new Promise(function (resolve, reject) {
    var revisionPath = _path2.default.join(_.config.root, _.config.data.url, filePath.replace('.' + _.config.files.templates.extension, '.json'));
    var postPath = _path2.default.join(_.config.root, _.config.publish.url, filePath);
    if (_.coreUtils.file.exist(revisionPath)) {
      var json = JSON.parse(JSON.stringify(_.cmsData.file.get(revisionPath)));
      if (json.abe_meta.publish != null) {
        delete json.abe_meta.publish;
      }

      var p = _.cmsOperations.post.draft(filePath, json, 'draft');

      p.then(function (result) {
        _.cmsOperations.remove.removeFile(revisionPath, postPath);
        _.abeExtend.hooks.instance.trigger('afterUnpublish', revisionPath, postPath);
        var newRevisionPath = _path2.default.join(_.config.root, _.config.data.url, result.json.abe_meta.latest.abeUrl.replace('.' + _.config.files.templates.extension, '.json'));
        _.Manager.instance.updatePostInList(newRevisionPath);
        resolve(result);
      }).catch(function (e) {
        console.error('[ERROR] unpublish', e);
        reject();
      });
    }
  });

  return p;
}

function submit(filePath, json, workflow) {
  var p;
  if (workflow === 'publish') {
    p = _.cmsOperations.post.publish(filePath, json);
  } else {
    p = _.cmsOperations.post.draft(filePath, json, workflow);
  }

  return p;
}

function reject(filePath, json, workflow) {
  _.abeExtend.hooks.instance.trigger('beforeReject', filePath);

  var rejectToWorkflow;
  var found = false;
  Array.prototype.forEach.call(_.config.users.workflow, function (flow) {
    if (workflow === flow) {
      found = true;
    }
    if (!found) {
      rejectToWorkflow = flow;
    }
  });
  if (!found) {
    rejectToWorkflow = 'draft';
  }

  var p = new Promise(function (resolve) {
    if (json.abe_meta.publish != null) {
      delete json.abe_meta.publish;
    }
    var p2 = _.cmsOperations.post.draft(filePath, json, rejectToWorkflow);
    p2.then(function (result) {
      _.abeExtend.hooks.instance.trigger('afterReject', result);
      resolve(result);
    }).catch(function (e) {
      console.error('[ERROR] reject.js', e);
    });
  });

  return p;
}