'use strict';

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

var _bluebird = require('bluebird');

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

var _pathExtra = require('path-extra');

function _asyncToGenerator(fn) { return function () { var gen = fn.apply(this, arguments); return new Promise(function (resolve, reject) { function step(key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { return Promise.resolve(value).then(function (value) { step("next", value); }, function (err) { step("throw", err); }); } } return step("next"); }); }; }

// A stream of async file writing. `write` queues the task which will be executed
// after all tasks before are done.
// Every instance contains an independent queue.
// Usage:
// var fw = new FileWriter()
// var path = '/path/to/a/file'
// for (var i = 0; i < 100; i++) {
//   fw.write(path, (''+i).repeat(10000))
// }
class FileWriter {
  constructor() {
    this.writing = false;
    this._queue = [];
  }

  write(path, data, options, callback) {
    this._queue.push([path, data, options, callback]);
    this._continueWriting();
  }

  _continueWriting() {
    var _this = this;

    return _asyncToGenerator(function* () {
      if (_this.writing) return;
      _this.writing = true;
      while (_this._queue.length) {
        const [path, data, options, callback] = _this._queue.shift();
        yield (0, _bluebird.promisify)(_fsExtra.ensureDir)((0, _pathExtra.dirname)(path));
        const err = yield (0, _bluebird.promisify)(_fsExtra.writeFile)(path, data, options);
        if (callback) callback(err);
      }
      _this.writing = false;
    })();
  }

}
exports.default = FileWriter;
module.exports = exports['default'];