'use strict';

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.getAbeMeta = getAbeMeta;
exports.getAllWithKeys = getAllWithKeys;
exports.get = get;
exports.fromUrl = fromUrl;
exports.getFilesByType = getFilesByType;
exports.getFileObject = getFileObject;

var _path = require('path');

var _path2 = _interopRequireDefault(_path);

var _mkdirp = require('mkdirp');

var _mkdirp2 = _interopRequireDefault(_mkdirp);

var _fsExtra = require('fs-extra');

var _fsExtra2 = _interopRequireDefault(_fsExtra);

var _moment = require('moment');

var _moment2 = _interopRequireDefault(_moment);

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

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

function getAbeMeta(fileObject, json) {
  var fileStatusIsPublish = _.cmsData.fileAttr.get(fileObject.cleanPath);

  if (json.abe_meta.latest.date != null) {
    fileObject.date = json.abe_meta.latest.date;
    fileObject.cleanDate = (0, _moment2.default)(json.abe_meta.latest.date).format('YYYY/MM/DD HH:mm:ss');
  }

  if (json.abe_meta != null) {
    if (json.abe_meta.status === 'publish') {
      fileObject.htmlPath = _path2.default.join(_.config.root, _.config.publish.url, _path2.default.join('/', fileObject.filePath.replace(/\.json/, '.' + _.config.files.templates.extension)));
    }
    var date = null;
    if (json.abe_meta.latest.date !== null) {
      date = json.abe_meta.latest.date;
    } else if (json.abe_meta.date !== null) {
      date = json.abe_meta.date;
    }
    fileObject.abe_meta = {
      date: date,
      type: json.abe_meta.type != null ? json.abe_meta.type : null,
      link: json.abe_meta.link != null ? json.abe_meta.link : null,
      template: json.abe_meta.template != null ? json.abe_meta.template : null,
      cleanName: json.abe_meta.cleanName != null ? json.abe_meta.cleanName : null,
      cleanFilename: json.abe_meta.cleanFilename != null ? json.abe_meta.cleanFilename : null,
      status: json.abe_meta.status != null ? json.abe_meta.status : null
    };
    if (fileStatusIsPublish.s != null && json.abe_meta.status === 'publish') {
      fileObject.abe_meta.status = 'draft';
    }
  }

  return fileObject;
}

function getAllWithKeys(withKeys) {
  var pathData = _path2.default.join(_.config.root, _.config.data.url);
  var extension = '.json';
  var files = _.coreUtils.file.getFilesSync(pathData, true, extension);

  var filesArr = [];

  Array.prototype.forEach.call(files, function (pathFile) {
    var json = _.cmsData.file.get(pathFile);
    var fileObject = _.cmsData.file.getFileObject(pathFile);
    fileObject = _.cmsData.file.getAbeMeta(fileObject, json);

    Array.prototype.forEach.call(withKeys, function (key) {
      var keyFirst = key.split('.')[0];
      fileObject[keyFirst] = json[keyFirst];
    });

    filesArr.push(fileObject);
  });

  var merged = _.cmsData.revision.getFilesMerged(filesArr);
  _.abeExtend.hooks.instance.trigger('afterGetAllFiles', merged);

  return merged;
}

function get(pathJson) {
  var json = void 0;
  pathJson = _.abeExtend.hooks.instance.trigger('beforeGetJson', pathJson);

  try {
    var stat = _fsExtra2.default.statSync(pathJson);
    if (stat) {
      json = _fsExtra2.default.readJsonSync(pathJson);
    }
  } catch (e) {
    json = {};
  }

  json = _.abeExtend.hooks.instance.trigger('afterGetJson', json);
  return json;
}

function fromUrl(url) {
  var res = {
    root: '',
    draft: {
      dir: '',
      file: '',
      path: ''
    },
    publish: {
      dir: '',
      file: '',
      link: '',
      path: '',
      json: ''
    },
    json: {
      path: '',
      file: ''
    }
  };

  if (url != null) {
    var dir = _path2.default.dirname(url).replace(_.config.root, '');
    var filename = _path2.default.basename(url);
    var pathDraft = _path2.default.join(_.config.root, _.config.draft.url, _path2.default.sep);
    var pathPublish = _path2.default.join(_.config.root, _.config.publish.url, _path2.default.sep);

    var link = url.replace(pathDraft, '');
    link = link.replace(pathPublish, '');
    link = link.replace(new RegExp('\\' + _path2.default.sep, 'g'), '/');
    link = _.cmsData.fileAttr.delete('/' + link);

    var publish = _.config.publish.url;
    var data = _.config.data.url;

    res.root = _.config.root;

    res.json.dir = _.coreUtils.file.changePath(dir, data);
    res.publish.dir = _.coreUtils.file.changePath(dir, publish);
    res.publish.json = res.json.dir;

    res.publish.file = _.cmsData.fileAttr.delete(filename);
    res.publish.link = link;
    res.json.file = filename.replace('.' + _.config.files.templates.extension, '.json');
    res.publish.json = _path2.default.join(res.json.dir, _.cmsData.fileAttr.delete(res.json.file));

    res.publish.path = _path2.default.join(res.publish.dir, res.publish.file);
    res.json.path = _path2.default.join(res.json.dir, res.json.file);
  }
  return res;
}

function getFilesByType(pathFile) {
  var type = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null;

  var extension = '.' + _.config.files.templates.extension;
  var result = [];

  try {
    var directory = _fsExtra2.default.lstatSync(pathFile);
    if (!directory.isDirectory()) {
      _mkdirp2.default.sync(pathFile);
    }
  } catch (e) {
    _mkdirp2.default.sync(pathFile);
  }
  var files = _.coreUtils.file.getFilesSync(pathFile, true, extension);

  Array.prototype.forEach.call(files, function (file) {
    var val = _.cmsData.fileAttr.get(file).s;
    if (type === null || val === type) result.push(file);
  });

  return result;
}

function getFileObject(pathFile) {
  var pathData = _path2.default.join(_.config.root, _.config.data.url);
  var extension = '.json';
  var templateExtension = '.' + _.config.files.templates.extension;

  var name = _path2.default.basename(pathFile);
  var relativePath = pathFile.replace(pathData + _path2.default.sep, '');

  var parentName = _.cmsData.fileAttr.delete(name);
  var parentRelativePath = _.cmsData.fileAttr.delete(pathFile).replace(pathData + _path2.default.sep, '');

  var fileData = _.cmsData.fileAttr.get(name);

  var date = void 0;
  if (fileData.d) {
    date = fileData.d;
  } else {
    var stat = _fsExtra2.default.statSync(pathFile);
    date = stat.mtime;
  }

  var fileDate = (0, _moment2.default)(date);
  var duration = _moment2.default.duration((0, _moment2.default)(fileDate).diff(new Date())).humanize(true);

  var htmlUrl = _path2.default.join('/', relativePath.replace(extension, templateExtension));

  var fileObject = {
    'name': name,
    'path': pathFile,
    'cleanPath': relativePath,
    'filePath': relativePath,
    'date': date,
    'cleanDate': fileDate.format('YYYY/MM/DD HH:mm:ss'),
    'duration': duration,
    'cleanName': parentName,
    'parentRelativePath': parentRelativePath,
    'html': htmlUrl
  };

  return fileObject;
}