"use strict";

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

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

var _watcher = _interopRequireDefault(require("watcher"));

var _runBabelForJSFile = require("../babel/runBabelForJSFile");

var _runPostCssForCssFile = require("../postcss/runPostCssForCssFile");

var _directoryIterator = require("./directoryIterator");

var _copyFile = require("./copyFile");

var _logger = require("../../logger");

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

const isJs = ext => ext === '.js';

const isCss = ext => ext === '.css';

function watchRun({
  options,
  src,
  target,
  canWatch,
  mode
}) {
  let updatedFileCount = 0;

  function doWorkForSeparateFile(filename) {
    const outputFile = filename.replace(src, target);

    const {
      ext
    } = _path.default.parse(filename);

    if (isJs(ext)) {
      (0, _runBabelForJSFile.runBabelForJSFile)({
        filename,
        outputFile,
        options,
        mode
      });
    } else if (isCss(ext)) {
      (0, _runPostCssForCssFile.runPostCssForCssFile)({
        filename,
        outputFile,
        options
      });
    } else {
      (0, _copyFile.copyFile)(filename, outputFile);
    }

    updatedFileCount++;
  }

  function doWork(foldername) {
    updatedFileCount = 0;
    const startTime = Date.now();
    (0, _directoryIterator.directoryIterator)(foldername, filename => {
      try {
        doWorkForSeparateFile(filename);
      } catch (error) {
        (0, _logger.messageLogger)(`ERROR In: ${filename}`);
        (0, _logger.messageLogger)(error);
      }
    });
    (0, _logger.messageLogger)(`Successfully compiled ${updatedFileCount} files with Babel and Post-CSS (${Date.now() - startTime}ms).`);
  }

  doWork(src);

  if (canWatch) {
    const watcher = new _watcher.default(src, {
      recursive: true,
      ignoreInitial: true,
      ignore: filename => filename.indexOf('__tests__') !== -1
    });
    watcher.on('all', (event, filename) => {
      if (event === 'unlink' || event === 'unlinkDir') {
        return;
      }

      doWork(filename); // This is what the library does internally when you pass it a handler directly
      //   arguments [0] (event); // => could be any target event: 'add', 'addDir', 'change', 'rename', 'renameDir', 'unlink' or 'unlinkDir'
      //   arguments [1] (filename); // => the file system path where the event took place, this is always provided
      //   arguments [2] (targetPathNext); // => the file system path "targetPath" got renamed to, this is only provided on 'rename'/'renameDir' events
    });
    watcher.on('error', error => {
      (0, _logger.messageLogger)(error); // => true, "Error" instances are always provided on "error"
    });
  }
}