'use strict';

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

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

var _fsExtra2 = _interopRequireDefault(_fsExtra);

var _dirCompare = require('dir-compare');

var _dirCompare2 = _interopRequireDefault(_dirCompare);

var _mkdirp = require('mkdirp');

var _mkdirp2 = _interopRequireDefault(_mkdirp);

var _path = require('path');

var _path2 = _interopRequireDefault(_path);

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

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

function copy() {
  var publicFolders = _.cmsTemplates.assets.getFolders();
  var publish = _.config.publish.url;
  var dest = _path2.default.join(_.config.root, publish);
  try {
    var directory = _fsExtra2.default.lstatSync(dest);
    if (!directory.isDirectory()) {
      _mkdirp2.default.sync(dest);
    }
  } catch (e) {
    _mkdirp2.default.sync(dest);
  }

  Array.prototype.forEach.call(publicFolders, function (publicFolder) {
    var res = _dirCompare2.default.compareSync(publicFolder, dest, { compareSize: true });

    res.diffSet.forEach(function (entry) {
      var state = {
        'equal': '==',
        'left': '->',
        'right': '<-',
        'distinct': '<>'
      }[entry.state];

      var name1 = entry.name1 ? entry.name1 : '';
      var name2 = entry.name2 ? entry.name2 : '';

      var exclude = new RegExp(_.config.files.exclude);
      if (!exclude.test(name1) && !exclude.test(name2) && entry.type1 !== 'directory' && entry.type2 !== 'directory') {

        if (typeof entry.path1 !== 'undefined' && entry.path1 !== null) {
          var original = entry.path1;
          var basePath = original.replace(publicFolder, '');
          var move = _path2.default.join(dest, basePath);

          if (entry.type2 === 'missing' || entry.state === 'distinct') {
            _fsExtra2.default.removeSync(move);
            _fsExtra2.default.copySync(original, move);
          }
        }
      }
    });
  });

  return publicFolders;
}

function getFolders() {
  var templateExtension = '.' + _.config.files.templates.extension;
  var assetsExtension = _.config.files.templates.assets;
  var pathAssets = _path2.default.join(_.config.root, _.config.templates.url);
  var assetsFolders = [];
  var files = _.coreUtils.file.getFilesSync(pathAssets, false, templateExtension);

  // now check if corresponding assets folder exist
  Array.prototype.forEach.call(files, function (file) {
    var folderName = file.replace(_path2.default.extname(file), assetsExtension);
    try {
      var directory = _fsExtra2.default.lstatSync(folderName);
      if (directory.isDirectory()) {
        assetsFolders.push(folderName);
      }
    } catch (e) {
      //No directory with this name
    }
  });

  return assetsFolders;
}