'use strict';

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

var _classCallCheck = require('@babel/runtime/helpers/classCallCheck');
var _createClass = require('@babel/runtime/helpers/createClass');
var _defineProperty = require('@babel/runtime/helpers/defineProperty');
var Constants = require('./Constants');
var fs = require('fs');
var nodeUtils = require('@teclone/node-utils');
var os = require('os');

function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }

function _interopNamespace(e) {
  if (e && e.__esModule) return e;
  var n = Object.create(null);
  if (e) {
    Object.keys(e).forEach(function (k) {
      if (k !== 'default') {
        var d = Object.getOwnPropertyDescriptor(e, k);
        Object.defineProperty(n, k, d.get ? d : {
          enumerable: true,
          get: function () {
            return e[k];
          }
        });
      }
    });
  }
  n['default'] = e;
  return Object.freeze(n);
}

var _classCallCheck__default = /*#__PURE__*/_interopDefaultLegacy(_classCallCheck);
var _createClass__default = /*#__PURE__*/_interopDefaultLegacy(_createClass);
var _defineProperty__default = /*#__PURE__*/_interopDefaultLegacy(_defineProperty);
var fs__namespace = /*#__PURE__*/_interopNamespace(fs);

var Logger = /*#__PURE__*/function () {
  function Logger(config) {
    _classCallCheck__default['default'](this, Logger);

    _defineProperty__default['default'](this, "config", void 0);

    _defineProperty__default['default'](this, "errorLogHandle", void 0);

    _defineProperty__default['default'](this, "accessLogHandle", void 0);

    this.config = config;
    var errorLogPath = nodeUtils.resolvePaths(this.config.entryPath, this.config.errorLog);
    var accessLogPath = nodeUtils.resolvePaths(this.config.entryPath, this.config.accessLog);
    nodeUtils.mkDirSync(errorLogPath);
    nodeUtils.mkDirSync(accessLogPath);
    this.errorLogHandle = fs__namespace.openSync(nodeUtils.resolvePaths(this.config.entryPath, this.config.errorLog), 'a');
    this.accessLogHandle = fs__namespace.openSync(nodeUtils.resolvePaths(this.config.entryPath, this.config.accessLog), 'a');
  }
  /**
   * close the handles once the server is closed
   */


  _createClass__default['default'](Logger, [{
    key: "close",
    value: function close() {
      fs__namespace.closeSync(this.errorLogHandle);
      fs__namespace.closeSync(this.accessLogHandle);
      return this;
    }
    /**
     * runs the error logging
     */

  }, {
    key: "logError",
    value: function logError(level, err) {
      var now = new Date();
      fs__namespace.writeSync(this.errorLogHandle, "[".concat(now.toUTCString(), "] [").concat(level, "] ").concat(err.stack).concat(os.EOL));
      return this;
    }
    /**
     * logs access information
     */

  }, {
    key: "logAccess",
    value: function logAccess(req, res) {
      var protocol = req.encrypted ? 'Https' : 'Http';
      var startTime = req.startedAt.toUTCString();
      var log = "[".concat(startTime, "] [").concat(req.method, "] '").concat(req.url, " ").concat(protocol, "/").concat(req.httpVersion, "' ").concat(res.statusCode).concat(os.EOL);
      fs__namespace.writeSync(this.accessLogHandle, log);
    }
    /**
     * log request response profile
     */

  }, {
    key: "profile",
    value: function profile(req, res) {
      this.logAccess(req, res);

      if (this.config.env === 'development' && this.config.profileRequest) {
        var requestTime = req.endedAt.getTime() - req.startedAt.getTime();
        var responseTime = res.endedAt.getTime() - res.startedAt.getTime();
        var template = res.statusCode >= 400 ? '%s: %s \x1b[31m%d\x1b[0m ~%dms ~%dms\x1b[0m %s' : '%s: %s \x1b[32m%d\x1b[0m ~%dms ~%dms\x1b[0m %s';
        console.log(template, req.method, req.url, res.statusCode, requestTime, responseTime, req.headers['user-agent']);
      }

      return this;
    }
    /**
     * logs fatal error to error log file and ends the response
     */

  }, {
    key: "fatal",
    value: function fatal(err) {
      this.logError(Constants.ERROR_LEVELS.FATAL, err); // const statusCode = this.config.env === 'prod' ? 500 : 200;
      // const data = this.config.env === 'prod' ? undefined : err.toString();
      // /* istanbul ignore else */
      // if (!response.finished) {
      //   return response
      //     .status(statusCode)
      //     .removeHeaders('Content-Length')
      //     .end(data);
      // } else {
      //   return Promise.resolve(false);
      // }
    }
    /**
     * log warning message to the console
     */

  }, {
    key: "warn",
    value: function warn(message) {
      console.log('\x1b[1m\x1b[31m%s\x1b[0m', message);
      return this;
    }
    /**
     * log info message to the console
     */

  }, {
    key: "info",
    value: function info(message) {
      console.log('\x1b[1m\x1b[32m%s\x1b[0m', message);
      return this;
    }
  }]);

  return Logger;
}();

exports.Logger = Logger;
//# sourceMappingURL=Logger.js.map
