"use strict";

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

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

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

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

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

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

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

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

var _regenerator = _interopRequireDefault(require("@babel/runtime/regenerator"));

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

var _react = _interopRequireDefault(require("react"));

var _propTypes = _interopRequireDefault(require("prop-types"));

var _clipboardCopy = _interopRequireDefault(require("clipboard-copy"));

var _Flex = _interopRequireDefault(require("../../components/Flex"));

var _Tabs = _interopRequireDefault(require("../../components/Tabs"));

var _Table = _interopRequireDefault(require("../../components/Table"));

var _Title = _interopRequireDefault(require("../../components/Title"));

var _Button = _interopRequireDefault(require("../../components/Button"));

var _HTTPStatus = _interopRequireDefault(require("../../components/HTTPStatus"));

var _ShowMore = _interopRequireDefault(require("../../components/ShowMore"));

function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = (0, _getPrototypeOf2["default"])(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = (0, _getPrototypeOf2["default"])(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return (0, _possibleConstructorReturn2["default"])(this, result); }; }

function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); return true; } catch (e) { return false; } }

// Style
var classes = {};
/* istanbul ignore next */

if (typeof window !== 'undefined') classes = require("./style.module.scss");

var WrapValuesInCode = function WrapValuesInCode(h) {
  if (typeof h.value === 'string') h.value = /*#__PURE__*/_react["default"].createElement("pre", {
    key: "H::".concat(h.name),
    className: classes['APILog-tableValue']
  }, h.value);
};

var copyHandler = /*#__PURE__*/function () {
  var _ref2 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee(_ref, body) {
    var target, copied, modifier;
    return _regenerator["default"].wrap(function _callee$(_context) {
      while (1) {
        switch (_context.prev = _context.next) {
          case 0:
            target = _ref.target;
            _context.next = 3;
            return (0, _clipboardCopy["default"])(body).then(function () {
              return 'OK';
            })["catch"](function () {
              return 'ERR';
            });

          case 3:
            copied = _context.sent;
            modifier = classes["APILog-copy_".concat(copied)];
            target.classList.add(modifier);
            setTimeout(function () {
              return target.classList.remove(modifier);
            }, 2500);

          case 7:
          case "end":
            return _context.stop();
        }
      }
    }, _callee);
  }));

  return function copyHandler(_x, _x2) {
    return _ref2.apply(this, arguments);
  };
}();

var ToggleHeaders = function ToggleHeaders(_ref3) {
  var text = _ref3.text,
      _ref3$theme = _ref3.theme,
      theme = _ref3$theme === void 0 ? 'shale' : _ref3$theme;
  return /*#__PURE__*/_react["default"].createElement(_Flex["default"], {
    layout: "row"
  }, /*#__PURE__*/_react["default"].createElement("small", null, /*#__PURE__*/_react["default"].createElement(_Button["default"], {
    bem: (0, _defineProperty2["default"])({}, theme, true),
    size: "sm"
  }, text)));
};

ToggleHeaders.propTypes = {
  text: _propTypes["default"].string,
  theme: _propTypes["default"].string
};

var APILogInfo = function APILogInfo(_ref5) {
  var link = _ref5.link,
      method = _ref5.method,
      startedDateTime = _ref5.startedDateTime,
      status = _ref5.status,
      url = _ref5.url;
  var datetime = startedDateTime ? new Date(startedDateTime) : false;
  return /*#__PURE__*/_react["default"].createElement(_react["default"].Fragment, null, /*#__PURE__*/_react["default"].createElement("div", {
    shift: "end",
    style: {
      overflow: 'hidden',
      textOverflow: 'ellipsis'
    }
  }, /*#__PURE__*/_react["default"].createElement("b", null, /*#__PURE__*/_react["default"].createElement(_HTTPStatus["default"], {
    status: status
  }), " ", /*#__PURE__*/_react["default"].createElement("code", null, method)), ' ', /*#__PURE__*/_react["default"].createElement("code", null, url), ' '), !datetime || /*#__PURE__*/_react["default"].createElement("span", {
    style: {
      opacity: 0.75,
      textAlign: 'right'
    }
  }, datetime.toLocaleDateString('en-US', {
    dateStyle: 'short'
  }), ', ', datetime.toLocaleTimeString('en-US', {
    timeStyle: 'short'
  }).replace(' ', '')), !link || /*#__PURE__*/_react["default"].createElement("a", {
    href: link,
    rel: "noopener noreferrer",
    style: {
      whiteSpace: 'nowrap'
    },
    target: "_blank"
  }, /*#__PURE__*/_react["default"].createElement("b", null, "View Docs")));
};

APILogInfo.propTypes = {
  link: _propTypes["default"].string,
  method: _propTypes["default"].string,
  startedDateTime: _propTypes["default"].string,
  status: _propTypes["default"].oneOfType([_propTypes["default"].number, _propTypes["default"].string]),
  url: _propTypes["default"].string
};

var APILogRequest = function APILogRequest(_ref6) {
  var _ref6$headers = _ref6.headers,
      headers = _ref6$headers === void 0 ? [] : _ref6$headers,
      _ref6$allHeaders = _ref6.allHeaders,
      allHeaders = _ref6$allHeaders === void 0 ? [] : _ref6$allHeaders,
      query = _ref6.query,
      curl = _ref6.curl;
  headers.forEach(WrapValuesInCode);
  allHeaders.forEach(WrapValuesInCode);
  query.forEach(WrapValuesInCode);
  return /*#__PURE__*/_react["default"].createElement(_react["default"].Fragment, null, /*#__PURE__*/_react["default"].createElement(_Title["default"], {
    level: 5
  }, "Body"), /*#__PURE__*/_react["default"].createElement("div", {
    style: {
      position: 'relative'
    }
  }, /*#__PURE__*/_react["default"].createElement(_Button["default"], {
    bem: {
      shale: !0
    },
    className: classes['APILog-copy'],
    onClick: function onClick(e) {
      return copyHandler(e, curl);
    },
    size: "sm",
    text: "Copy"
  }), /*#__PURE__*/_react["default"].createElement("pre", null, curl)), /*#__PURE__*/_react["default"].createElement(_Title["default"], {
    level: 5
  }, "Headers"), /*#__PURE__*/_react["default"].createElement("div", null, headers.length > 0 && /*#__PURE__*/_react["default"].createElement(_Table["default"], {
    body: headers,
    pick: ['name', 'value']
  }), !allHeaders.length || /*#__PURE__*/_react["default"].createElement(_ShowMore["default"], {
    height: "8em",
    label: /*#__PURE__*/_react["default"].createElement(ToggleHeaders, {
      text: "All..."
    }),
    labelClose: /*#__PURE__*/_react["default"].createElement(ToggleHeaders, {
      text: "Less...",
      theme: "shale_ghost"
    })
  }, /*#__PURE__*/_react["default"].createElement(_Table["default"], {
    body: allHeaders,
    pick: ['name', 'value']
  }))), query.length && /*#__PURE__*/_react["default"].createElement(_react["default"].Fragment, null, /*#__PURE__*/_react["default"].createElement(_Title["default"], {
    level: 5
  }, "Query Parameters"), /*#__PURE__*/_react["default"].createElement(_Table["default"], {
    body: query,
    pick: ['name', 'value']
  })) || '');
};

APILogRequest.propTypes = {
  allHeaders: _propTypes["default"].array,
  curl: _propTypes["default"].string,
  headers: _propTypes["default"].array,
  query: _propTypes["default"].array
};

var APILogResponse = function APILogResponse(_ref7) {
  var _ref7$headers = _ref7.headers,
      headers = _ref7$headers === void 0 ? [] : _ref7$headers,
      _ref7$allHeaders = _ref7.allHeaders,
      allHeaders = _ref7$allHeaders === void 0 ? [] : _ref7$allHeaders,
      json = _ref7.json;
  var body = JSON.stringify(JSON.parse(json), null, 2);
  headers.forEach(WrapValuesInCode);
  allHeaders.forEach(WrapValuesInCode);
  return /*#__PURE__*/_react["default"].createElement(_react["default"].Fragment, null, /*#__PURE__*/_react["default"].createElement(_Title["default"], {
    level: 5
  }, "Body"), /*#__PURE__*/_react["default"].createElement("div", {
    style: {
      position: 'relative'
    }
  }, /*#__PURE__*/_react["default"].createElement(_Button["default"], {
    bem: {
      shale: !0
    },
    className: classes['APILog-copy'],
    onClick: function onClick(e) {
      return copyHandler(e, body);
    },
    size: "sm",
    text: "Copy"
  }), /*#__PURE__*/_react["default"].createElement("pre", null, body)), /*#__PURE__*/_react["default"].createElement(_Title["default"], {
    level: 5
  }, "Headers"), /*#__PURE__*/_react["default"].createElement("div", null,
  /* istanbul ignore next */
  !headers.length || /*#__PURE__*/_react["default"].createElement(_Table["default"], {
    body: headers,
    pick: ['name', 'value']
  }), !allHeaders.length || /*#__PURE__*/_react["default"].createElement(_ShowMore["default"], {
    height: "8em",
    label: /*#__PURE__*/_react["default"].createElement(ToggleHeaders, {
      text: "All...",
      theme: "shale_ghost"
    }),
    labelClose: /*#__PURE__*/_react["default"].createElement(ToggleHeaders, {
      text: "Less..."
    })
  }, /*#__PURE__*/_react["default"].createElement(_Table["default"], {
    body: allHeaders,
    pick: ['name', 'value']
  }))));
};

APILogResponse.propTypes = {
  allHeaders: _propTypes["default"].array,
  headers: _propTypes["default"].array,
  json: _propTypes["default"].string
};

var APILog = /*#__PURE__*/function (_React$Component) {
  (0, _inherits2["default"])(APILog, _React$Component);

  var _super = _createSuper(APILog);

  function APILog(props) {
    var _this;

    (0, _classCallCheck2["default"])(this, APILog);
    _this = _super.call(this, props);
    _this.curl = props.log.curl || 'No cURL available.';
    return _this;
  }

  (0, _createClass2["default"])(APILog, [{
    key: "render",
    value: function render() {
      var _this$props = this.props,
          log = _this$props.log,
          link = _this$props.link;
      var status = log.status,
          _log$startedDateTime = log.startedDateTime,
          startedDateTime = _log$startedDateTime === void 0 ? '' : _log$startedDateTime,
          requestHeaders = log.requestHeaders,
          queryString = log.queryString,
          method = log.method,
          url = log.url;
      return /*#__PURE__*/_react["default"].createElement(_Flex["default"], {
        align: "stretch",
        className: classes.APILog,
        layout: "col",
        style: this.props.style
      }, /*#__PURE__*/_react["default"].createElement(_Flex["default"], {
        align: "center",
        className: classes['APILog-info']
      }, /*#__PURE__*/_react["default"].createElement(APILogInfo, {
        link: link,
        method: method,
        startedDateTime: startedDateTime,
        status: status,
        url: url
      })), /*#__PURE__*/_react["default"].createElement(_Tabs["default"], {
        className: {
          root: 'Flex_inner',
          tabs: classes['APILog-tabs']
        }
      }, /*#__PURE__*/_react["default"].createElement("div", {
        label: "Request"
      }, /*#__PURE__*/_react["default"].createElement(APILogRequest, {
        allHeaders: log.fullReqHeaders,
        curl: this.curl,
        headers: requestHeaders,
        query: queryString
      })), /*#__PURE__*/_react["default"].createElement("div", {
        label: "Response"
      }, /*#__PURE__*/_react["default"].createElement(APILogResponse, {
        allHeaders: log.fullResHeaders,
        headers: log.responseHeaders,
        json: log.responseBody.text
      }))));
    }
  }]);
  return APILog;
}(_react["default"].Component);

(0, _defineProperty2["default"])(APILog, "propTypes", {
  link: _propTypes["default"].string,
  log: _propTypes["default"].shape({
    curl: _propTypes["default"].string,
    fullReqHeaders: _propTypes["default"].array,
    fullResHeaders: _propTypes["default"].array,
    method: _propTypes["default"].oneOfType([_propTypes["default"].number, _propTypes["default"].string]),
    queryString: _propTypes["default"].array,
    requestHeaders: _propTypes["default"].array,
    response: _propTypes["default"].object,
    responseBody: _propTypes["default"].object,
    responseHeaders: _propTypes["default"].array,
    startedDateTime: _propTypes["default"].string,
    status: _propTypes["default"].oneOfType([_propTypes["default"].number, _propTypes["default"].string]),
    url: _propTypes["default"].string
  })
});
var _default = APILog;
exports["default"] = _default;