"use strict";

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

var _path = _interopRequireDefault(require("path"));

var _copyWebpackPlugin = _interopRequireDefault(require("copy-webpack-plugin"));

var _fs = require("fs");

var _updateArrayWithDefault = require("../utils/updateArrayWithDefault");

var _constants = require("../../../constants");

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

const defaultPublicFolders = [{
  // source must be relative path  not absolute path
  source: 'public',
  // target is the path that this copied file output path
  target: 'public',
  toType: 'dir'
}];

function folderPatterns(publicFolders) {
  return publicFolders.map(conf => {
    const tpFolderActualPath = (0, _constants.joinWithAppPath)(conf.source);

    if (!conf.source || !conf.target || _path.default.isAbsolute(conf.source) || !(0, _fs.existsSync)(tpFolderActualPath)) {
      // console.log(tpFolderActualPath, 'not exist', tpFolder);
      return null;
    }

    return {
      from: tpFolderActualPath,
      to: conf.target,
      toType: conf.toType || 'dir'
    };
  }).filter(Boolean);
}

function configCopyPublicFolders(options) {
  let {
    publicFolders
  } = options;
  const {
    context
  } = options;
  const {
    tpFolder
  } = options.app;

  if (tpFolder) {
    const tpConfig = {
      from: `${context}/${tpFolder}`,
      to: `${tpFolder}`,
      toType: 'dir'
    };
    publicFolders.push(tpConfig);
  }

  publicFolders = (0, _updateArrayWithDefault.updateArrayWithDefault)(publicFolders, defaultPublicFolders);

  if (publicFolders.length === 0) {
    return null;
  }

  const patterns = folderPatterns(publicFolders);

  if (patterns.length === 0) {
    return null;
  }

  return new _copyWebpackPlugin.default({
    patterns
  });
}