'use strict';

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

var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };

exports.exist = exist;
exports.changePath = changePath;
exports.getContent = getContent;
exports.getFoldersSync = getFoldersSync;
exports.getFoldersAsync = getFoldersAsync;
exports.getFilesSync = getFilesSync;
exports.getFilesAsync = getFilesAsync;
exports.addFolder = addFolder;
exports.removeFolder = removeFolder;
exports.getDate = getDate;
exports.addDateIsoToRevisionPath = addDateIsoToRevisionPath;

var _bluebird = require('bluebird');

var _bluebird2 = _interopRequireDefault(_bluebird);

var _path = require('path');

var _path2 = _interopRequireDefault(_path);

var _mkdirp = require('mkdirp');

var _mkdirp2 = _interopRequireDefault(_mkdirp);

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

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

var fse = _bluebird2.default.promisifyAll(require('fs-extra'));

function exist(pathFile) {
  try {
    fse.statSync(pathFile);
    return true;
  } catch (e) {
    return false;
  }
}

function changePath(pathEnv, change) {
  pathEnv = pathEnv.split(_path2.default.sep).join('/').replace(_.config.root, '').replace(/^\//, '').split('/');
  pathEnv[0] = change;
  return _path2.default.join(_.config.root, pathEnv.join('/'));
}

/**
 * This method checks that the path leads to a file and return the content as UTF-8 content
 * @param  {string} path The path
 * @return {string}      The content of the UTF-8 file
 */
function getContent(pathFile) {
  var res = null;
  if (typeof pathFile !== 'undefined' && pathFile !== null && pathFile !== '') {
    if (exist(pathFile)) {
      res = fse.readFileSync(pathFile, 'utf8');
    }
  }
  return res;
}

/**
 * synchronous fse walker to get folders with recursive option
 * @param  {String}  dirname   dir path
 * @param  {Boolean} recursive do we recurse in the subfolders
 * @param  {String}  filterExt extension or ''
 * @return {array}             array of pathfiles
 */
function getFoldersSync(dirname) {
  var recursive = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;

  var items = [];
  try {
    fse.readdirSync(dirname).map(function (fileName) {
      var pathFile = _path2.default.join(dirname, fileName);
      var stat = fse.statSync(pathFile);
      if (stat.isDirectory()) {
        var directory = { 'path': pathFile, 'folders': [] };
        if (recursive) {
          directory.folders = _.coreUtils.file.getFoldersSync(pathFile, recursive);
        }
        items.push(directory);
      }
    });

    return items;
  } catch (e) {

    return items;
  }
}

/**
 * Promisified fse walker to get folders with recursive option
 * @param  {String}  dirname   dir path
 * @param  {Boolean} recursive do we recurse in the subfolders
 * @param  {String}  filterExt extension or ''
 * @return {array}             array of pathfiles
 */
function getFoldersAsync(dirname) {
  var recursive = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;

  var items = [];
  return fse.readdirAsync(dirname).map(function (fileName) {
    var pathFile = _path2.default.join(dirname, fileName);
    return fse.statAsync(pathFile).then(function (stat) {
      if (stat.isDirectory()) {
        var _ret = function () {
          var directory = { 'path': pathFile, 'folders': [] };

          if (recursive) {
            return {
              v: _.coreUtils.file.getFoldersAsync(pathFile, recursive).then(function (filesInDir) {
                directory.folders = filesInDir;
                items.push(directory);
              })
            };
          } else {
            items.push(directory);
          }
        }();

        if ((typeof _ret === 'undefined' ? 'undefined' : _typeof(_ret)) === "object") return _ret.v;
      }
      return;
    });
  }).then(function () {
    return items;
  });
}

/**
 * synchronous fse walker with recursive and extension options
 * @param  {String}  dirname   dir path
 * @param  {Boolean} recursive do we recurse in the subfolders
 * @param  {String}  filterExt extension or ''
 * @return {array}             array of pathfiles
 */
function getFilesSync(dirname) {
  var recursive = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;
  var filterExt = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : '';

  var items = [];
  try {
    fse.readdirSync(dirname).map(function (fileName) {
      var pathFile = _path2.default.join(dirname, fileName);
      var stat = fse.statSync(pathFile);
      if (stat.isFile()) {
        var extFile = _path2.default.extname(fileName);
        if (filterExt === '' || extFile === filterExt) {
          items.push(pathFile);
        }
      }
      if (stat.isDirectory() && recursive) {
        var filesInDir = _.coreUtils.file.getFilesSync(pathFile, recursive, filterExt);
        items = items.concat(filesInDir);
      }
    });

    return items;
  } catch (e) {

    return items;
  }
}

/**
 * Promisified fse walker with recursive and extension options
 * @param  {String}  dirname   dir path
 * @param  {Boolean} recursive do we recurse in the subfolders
 * @param  {String}  filterExt extension or ''
 * @return {array}             array of pathfiles
 */
function getFilesAsync(dirname) {
  var recursive = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;
  var filterExt = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : '';

  var items = [];
  return fse.readdirAsync(dirname).map(function (fileName) {
    var pathFile = _path2.default.join(dirname, fileName);
    return fse.statAsync(pathFile).then(function (stat) {
      if (stat.isFile()) {
        var extFile = _path2.default.extname(fileName);
        if (filterExt === '' || extFile === filterExt) {
          return items.push(pathFile);
        }
        return;
      }
      if (recursive) {
        return _.coreUtils.file.getFilesAsync(pathFile, recursive, filterExt).then(function (filesInDir) {
          items = items.concat(filesInDir);
        });
      }
    });
  }).then(function () {
    return items;
  });
}

function addFolder(folderPath) {
  (0, _mkdirp2.default)(_path2.default.join(_.config.root, folderPath), function (err) {
    if (err) console.error(err);
  });
  return folderPath;
}

function removeFolder(folderPath) {
  fse.remove(_path2.default.join(_.config.root, folderPath), function (err) {
    if (err) return console.error(err);
  });
  return folderPath;
}

/**
 * Return the date of the revision
 * @param  {String}  revisionPath   url of the post revision
 * @return {Date}    date           Date object
 */
function getDate(revisionPath) {
  var date = _.cmsData.fileAttr.get(revisionPath).d;

  if (typeof date === 'undefined' || date === null || date === '') {
    date = new Date();
  } else {
    date = new Date(date);
  }

  return date;
}

/**
 * 
 * @param  {String}  revisionPath   url of the post revision
 * @return {Date}    date           Date object
 */
function addDateIsoToRevisionPath(revisionPath, type) {
  var dateISO;
  var saveJsonFile = revisionPath;

  if (type === 'publish') {
    return revisionPath;
  }

  dateISO = type[0] + _.cmsData.revision.removeStatusAndDateFromFileName(new Date().toISOString());

  if (dateISO) {
    saveJsonFile = _.cmsData.fileAttr.add(saveJsonFile, dateISO);
  }

  return saveJsonFile;
}