'use strict';
var fs = require('fs-extra');
var pack = require('tar-pack').pack;
var path = require('path');
var _ = require('lodash');

const REGEXP_RESOURCE = /(\/?resources)\S*?\.(png|gif|jpeg|jpg){1}/gi;
const IGNORE = ['node_modules/', 'datav_modules/', '.cubecache', 'children/', '.idea', 'package-lock.json', '.vscode'];

/**
 *
 * @param {any} value
 * @returns {array}
 */
function loopConfig(config) {
  if (!config) return null;
  let res = [];
  _.forIn(config, (value, key) => {
    if ((value.type === 'image' || value.type === 'hidden') && REGEXP_RESOURCE.test(value.default)) {
      res.push(value.default);
    } else if (value.type === 'group' && value.children) {
      res.concat(loopConfig(value.children));
    } else if (value.type === 'array' && value.child) {
      res.concat(loopConfig(value.child));
    }
  });
  return res;
}

/**
 * 根据配置选择性将resources文件夹下的内容挑选出来打包，避免临时文件被打包
 * @param {object} config
 * @returns {array}
 */
function clearResource(config, fileRoot, sysConfig) {
  let all = []
  if (fs.existsSync(fileRoot)) {
    all = _.map(fs.readdirSync(fileRoot), (url) => {
      return path.join('/', sysConfig.resourceDir, url);
    });
    let exclude = loopConfig(config);

    all = _.difference(all, exclude);
  }
  return all;
}

module.exports = function (config, tarPath, root, sysConfig, callback) {
  tarPath = path.join(tarPath, '/' + config.name.replace('/', '#') + '-' + config.version + '.tar.gz');

  return pack(root, {
    filter: function (entry) {
      const entryPath = entry.path.replace(root, '');
      return _.every(IGNORE, (rule) => {
        return entryPath.indexOf(rule) === -1;
      });
    }
  }).pipe(fs.createOutputStream(tarPath)).on('error', function (err) {
    callback(err);
  }).on('close', function () {
    callback(null, tarPath);
  });
};
