'use strict';

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.getFilesRevision = getFilesRevision;
exports.getVersions = getVersions;
exports.getDocumentRevision = getDocumentRevision;
exports.getStatusAndDateToFileName = getStatusAndDateToFileName;
exports.removeStatusAndDateFromFileName = removeStatusAndDateFromFileName;
exports.filePathInfos = filePathInfos;
exports.mergeRevisions = mergeRevisions;
exports.sortRevisions = sortRevisions;
exports.getFilesMerged = getFilesMerged;

var _path = require('path');

var _path2 = _interopRequireDefault(_path);

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

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

function getFilesRevision(urls, fileName) {
  var res = [];
  var number = 1;
  var tplUrl = _.cmsData.file.fromUrl(fileName);
  fileName = fileName.split('/');
  fileName = fileName[fileName.length - 1];
  var publishDate = new Date();
  var json = null;

  if (_.coreUtils.file.exist(tplUrl.publish.json)) {
    json = _.cmsData.file.get(tplUrl.publish.json);
    if (json != null && json[_.config.meta.name] != null) {
      publishDate = new Date(json[_.config.meta.name].latest.date);
    }
  }

  var publishVersion = false;
  urls.forEach(function (urlObj) {
    var fileData = _.cmsData.fileAttr.get(urlObj.cleanPath);
    if (fileData.s === 'd' && _.cmsData.fileAttr.delete(urlObj.cleanPath) == _.cmsData.fileAttr.delete(fileName)) {
      var currentDate = new Date(urlObj.date);
      if (currentDate.getTime() > publishDate.getTime()) {
        if (!publishVersion && res[res.length - 1] != null) {
          res[res.length - 1].publishedDate = 'same';
        }
        publishVersion = true;
        urlObj.publishedDate = 'after';
      } else if (currentDate.getTime() === publishDate.getTime()) {
        urlObj.publishedDate = 'same';
        publishVersion = true;
      } else {
        urlObj.publishedDate = 'before';
      }
      urlObj.version = number;
      number = number + 1;

      var tplUrlObj = _.cmsData.file.fromUrl(urlObj.path);
      if (_.coreUtils.file.exist(tplUrlObj.publish.json)) {
        var jsonObj = _.cmsData.file.get(tplUrlObj.publish.json);
        urlObj[_.config.meta.name] = jsonObj[_.config.meta.name];
      }
      res.push(urlObj);
    }
  });
  return res;
}

/**
 * Create and array of doc file path containing the versions of this doc
 * @param  {String} path of a doc
 * @return {Array} the versions of the doc
 */
function getVersions(docPath) {
  var result = [];
  var files = _.Manager.instance.getList();
  var dataFile = _path2.default.join(_.config.data.url, docPath.replace('.' + _.config.files.templates.extension, '.json'));
  Array.prototype.forEach.call(files, function (file) {
    if (file.path.indexOf(dataFile) > -1) {
      result = file.revisions;
    }
  });
  return result;
}

/**
 * Return the revision from document html file path
 * if the docPath contains abe revision [status]-[date] will try to return this revision
 * else it will return the latest revision
 * or null
 * 
 * @param  {String} html path
 * @return {Object} file revision | null
 */
function getDocumentRevision(docPath) {
  var result = null;
  var documentPath = docPath;
  var latest = true;

  if (_.cmsData.fileAttr.test(documentPath)) {
    latest = false;
    documentPath = _.cmsData.fileAttr.delete(documentPath);
  }
  var revisions = getVersions(documentPath);
  if (latest && revisions.length >= 0) {
    result = revisions[0];
  } else if (!latest) {
    Array.prototype.forEach.call(revisions, function (revision) {
      if (revision.html === docPath) {
        result = revision;
      }
    });
    if (result === null && revisions.length >= 0) {
      result = revisions[0];
    }
  }

  return result;
}

function getStatusAndDateToFileName(date) {
  var res = date.substring(0, 4) + '-' + date.substring(4, 6) + '-' + date.substring(6, 11) + ':' + date.substring(11, 13) + ':' + date.substring(13, 15) + '.' + date.substring(15, 19);
  return res;
}

function removeStatusAndDateFromFileName(date) {
  return date.replace(/[-:\.]/g, '');
}

function filePathInfos(pathFolder) {
  var pathArr = pathFolder.split('/');
  var name = pathArr[pathArr.length - 1];

  var rootArr = _.config.root.split('/');
  var website = rootArr[pathArr.length - 1];
  return {
    'name': name,
    'path': pathFolder,
    'website': website,
    'cleanPath': pathFolder.replace(_.config.root, '').replace(/\/$/, ''),
    'type': 'folder'
  };
}

function mergeRevisions(files) {
  var merged = {};

  Array.prototype.forEach.call(files, function (file) {
    var parentRelativePath = file.parentRelativePath;

    if (merged[parentRelativePath] == null) {
      merged[parentRelativePath] = {
        name: _.cmsData.fileAttr.delete(file.name),
        path: _.cmsData.fileAttr.delete(file.path),
        html: _.cmsData.fileAttr.delete(_path2.default.join('/', file.filePath.replace(/\.json/, '.' + _.config.files.templates.extension))),
        htmlPath: _path2.default.join(_.config.root, _.config.publish.url, _path2.default.join('/', _.cmsData.fileAttr.delete(file.filePath.replace(/\.json/, '.' + _.config.files.templates.extension)))),
        cleanPath: file.cleanPath,
        cleanName: file.cleanName,
        parentRelativePath: file.parentRelativePath,
        filePath: _.cmsData.fileAttr.delete(file.filePath),
        revisions: []
      };
    }
    merged[parentRelativePath].revisions.push(JSON.parse(JSON.stringify(file)));
  });

  return merged;
}

function sortRevisions(merged) {
  var sortedArray = [];

  Array.prototype.forEach.call(Object.keys(merged), function (key) {
    var revisions = merged[key].revisions;
    revisions.sort(_.coreUtils.sort.predicatBy('date', -1));
    merged[key].revisions = revisions;

    if (revisions[0] != null) {
      merged[key].date = revisions[0].date;
      merged[key].cleanDate = revisions[0].cleanDate;
      merged[key].duration = revisions[0].duration;
      merged[key].abe_meta = revisions[0].abe_meta;
    }

    var newStatuses = [];
    Array.prototype.forEach.call(revisions, function (revision) {
      var revisionStatus = revision.abe_meta.status;

      if (typeof revisionStatus !== 'undefined' && revisionStatus !== null && revisionStatus != '') {
        if (!(revisionStatus in newStatuses)) {
          if (revisionStatus === 'publish') {
            merged[key][revisionStatus] = revision;
          } else {
            merged[key][revisionStatus] = {};
          }
          merged[key][revisionStatus].path = revision.path;
          merged[key][revisionStatus].html = revision.html;
          merged[key][revisionStatus].htmlPath = revision.htmlPath;
          merged[key][revisionStatus].date = revision.date;
          merged[key][revisionStatus].cleanDate = revision.cleanDate;
          merged[key][revisionStatus].link = revision.abe_meta.link;

          newStatuses[revisionStatus] = true;
        }
      }
    });

    sortedArray.push(merged[key]);
  });

  return sortedArray;
}

function getFilesMerged(files) {
  var revisions = _.cmsData.revision.mergeRevisions(files);

  return _.cmsData.revision.sortRevisions(revisions);
}