"use strict";

var _postcss = _interopRequireDefault(require("postcss"));

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

var _fs = _interopRequireDefault(require("fs"));

var _folderIterator = _interopRequireDefault(require("./folderIterator"));

var _postcssRtl = _interopRequireDefault(require("@zohodesk/postcss-rtl"));

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

let cwd = process.cwd();

let src = _path.default.join(cwd, process.argv[2]);

let dist = _path.default.join(cwd, process.argv[3]);

let canWacth = '-w' === process.argv[4];

// import { useExitCleanup } from './useExitCleanup';
function watchHandler(fromPath, toPath) {
  let css = _fs.default.readFileSync(fromPath);

  (0, _postcss.default)([(0, _postcssRtl.default)({
    addPrefixToSelector: function addPrefixToSelector(selector, prefix) {
      if (prefix === '[dir]') {
        return selector;
      }

      return `${prefix} ${selector}`; // Make selectors like [dir=rtl] > .selector
    }
  })]).process(css, {
    from: fromPath,
    to: toPath
  }).then(result => {
    _fs.default.writeFile(toPath, result.css, () => true);

    if (result.map) {
      _fs.default.writeFile(`${toPath}.map`, result.map, () => true);
    }
  });
}

(0, _folderIterator.default)(src, dist, ['.css'], false, (fromPath, toPath) => {
  if (canWacth && fromPath) {
    _fs.default.watchFile(fromPath, () => {
      watchHandler(fromPath, toPath);
    });
  }

  watchHandler(fromPath, toPath);
}); // if (canWacth) {
//   useExitCleanup(() => {
//     fs.unwatchFile(src, watchHandler);
//   });
// }