"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");

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

function _bluebird() {
  const data = require("bluebird");

  _bluebird = function () {
    return data;
  };

  return data;
}

function _defineProperty2() {
  const data = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));

  _defineProperty2 = function () {
    return data;
  };

  return data;
}

function _fsExtra() {
  const data = _interopRequireDefault(require("fs-extra"));

  _fsExtra = function () {
    return data;
  };

  return data;
}

function _abstractVinyl() {
  const data = _interopRequireDefault(require("./abstract-vinyl"));

  _abstractVinyl = function () {
    return data;
  };

  return data;
}

function _validationError() {
  const data = _interopRequireDefault(require("../../../error/validation-error"));

  _validationError = function () {
    return data;
  };

  return data;
}

function _logger() {
  const data = _interopRequireDefault(require("../../../logger/logger"));

  _logger = function () {
    return data;
  };

  return data;
}

class JSONFile extends _abstractVinyl().default {
  constructor(...args) {
    super(...args);
    (0, _defineProperty2().default)(this, "override", false);
  }

  write() {
    var _this = this;

    return (0, _bluebird().coroutine)(function* () {
      const stat = yield _this._getStatIfFileExists();

      if (stat) {
        if (stat.isSymbolicLink()) {
          throw new (_validationError().default)(`fatal: trying to write a json file into a symlink file at "${_this.path}"`);
        }

        if (!_this.override) {
          _logger().default.debug(`json-file.write, ignore existing file ${_this.path}`);

          return _this.path;
        }
      }

      _logger().default.debug(`json-file.write, path ${_this.path}`);

      yield _fsExtra().default.outputFile(_this.path, _this.contents);
      return _this.path;
    })();
  }

  static load({
    base,
    path,
    content,
    override = false
  }) {
    const jsonStr = JSON.stringify(content, null, 4);
    const jsonFile = new JSONFile({
      base,
      path,
      contents: Buffer.from(jsonStr)
    });
    jsonFile.override = override;
    return jsonFile;
  }

}

exports.default = JSONFile;