'use strict';

exports.__esModule = true;

var _regenerator = require('babel-runtime/regenerator');

var _regenerator2 = _interopRequireDefault(_regenerator);

var _styleModule = require('./style.module.scss');

var _styleModule2 = _interopRequireDefault(_styleModule);

var _react = require('react');

var _react2 = _interopRequireDefault(_react);

var _propTypes = require('prop-types');

var _propTypes2 = _interopRequireDefault(_propTypes);

var _clipboardCopy = require('clipboard-copy');

var _clipboardCopy2 = _interopRequireDefault(_clipboardCopy);

var _Flex = require('../../components/Flex');

var _Flex2 = _interopRequireDefault(_Flex);

var _Tabs = require('../../components/Tabs');

var _Tabs2 = _interopRequireDefault(_Tabs);

var _Table = require('../../components/Table');

var _Table2 = _interopRequireDefault(_Table);

var _Title = require('../../components/Title');

var _Title2 = _interopRequireDefault(_Title);

var _Button = require('../../components/Button');

var _Button2 = _interopRequireDefault(_Button);

var _HTTPStatus = require('../../components/HTTPStatus');

var _HTTPStatus2 = _interopRequireDefault(_HTTPStatus);

var _ShowMore = require('../../components/ShowMore');

var _ShowMore2 = _interopRequireDefault(_ShowMore);

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

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

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"); }); }; }

var WrapValuesInCode = function WrapValuesInCode(h) {
  if (typeof h.value === 'string') h.value = _react2.default.createElement(
    'pre',
    { key: 'H::' + h.name, className: _styleModule2.default['APILog-tableValue'] },
    h.value
  );
};

var copyHandler = function () {
  var _ref = _asyncToGenerator( /*#__PURE__*/_regenerator2.default.mark(function _callee(_ref2, body) {
    var target = _ref2.target;
    var copied, modifier;
    return _regenerator2.default.wrap(function _callee$(_context) {
      while (1) {
        switch (_context.prev = _context.next) {
          case 0:
            _context.next = 2;
            return (0, _clipboardCopy2.default)(body).then(function () {
              return 'OK';
            }).catch(function () {
              return 'ERR';
            });

          case 2:
            copied = _context.sent;
            modifier = _styleModule2.default['APILog-copy_' + copied];

            target.classList.add(modifier);
            setTimeout(function () {
              return target.classList.remove(modifier);
            }, 2500);

          case 6:
          case 'end':
            return _context.stop();
        }
      }
    }, _callee, undefined);
  }));

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

var ToggleHeaders = function ToggleHeaders(_ref3) {
  var _ref4;

  var text = _ref3.text,
      _ref3$theme = _ref3.theme,
      theme = _ref3$theme === undefined ? 'shale' : _ref3$theme;
  return _react2.default.createElement(
    _Flex2.default,
    { layout: 'row' },
    _react2.default.createElement(
      'small',
      null,
      _react2.default.createElement(
        _Button2.default,
        { bem: (_ref4 = {}, _ref4[theme] = true, _ref4), size: 'sm' },
        text
      )
    )
  );
};
ToggleHeaders.propTypes = process.env.NODE_ENV !== "production" ? { text: _propTypes2.default.string, theme: _propTypes2.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 _react2.default.createElement(
    _react2.default.Fragment,
    null,
    _react2.default.createElement(
      'div',
      { shift: 'end', style: { overflow: 'hidden', textOverflow: 'ellipsis' } },
      _react2.default.createElement(
        'b',
        null,
        _react2.default.createElement(_HTTPStatus2.default, { status: status }),
        ' ',
        _react2.default.createElement(
          'code',
          null,
          method
        )
      ),
      ' ',
      _react2.default.createElement(
        'code',
        null,
        url
      ),
      ' '
    ),
    !datetime || _react2.default.createElement(
      'span',
      { style: { opacity: 0.75, textAlign: 'right' } },
      datetime.toLocaleDateString('en-US', { dateStyle: 'short' }),
      ', ',
      datetime.toLocaleTimeString('en-US', { timeStyle: 'short' }).replace(' ', '')
    ),
    !link || _react2.default.createElement(
      'a',
      { href: link, rel: 'noopener noreferrer', style: { whiteSpace: 'nowrap' }, target: '_blank' },
      _react2.default.createElement(
        'b',
        null,
        'View Docs'
      )
    )
  );
};
APILogInfo.propTypes = process.env.NODE_ENV !== "production" ? {
  link: _propTypes2.default.string,
  method: _propTypes2.default.string,
  startedDateTime: _propTypes2.default.string,
  status: _propTypes2.default.oneOfType([_propTypes2.default.number, _propTypes2.default.string]),
  url: _propTypes2.default.string
} : {};

var APILogRequest = function APILogRequest(_ref6) {
  var _ref6$headers = _ref6.headers,
      headers = _ref6$headers === undefined ? [] : _ref6$headers,
      _ref6$allHeaders = _ref6.allHeaders,
      allHeaders = _ref6$allHeaders === undefined ? [] : _ref6$allHeaders,
      query = _ref6.query,
      curl = _ref6.curl;

  headers.forEach(WrapValuesInCode);
  allHeaders.forEach(WrapValuesInCode);
  query.forEach(WrapValuesInCode);

  return _react2.default.createElement(
    _react2.default.Fragment,
    null,
    _react2.default.createElement(
      _Title2.default,
      { level: 5 },
      'Body'
    ),
    _react2.default.createElement(
      'div',
      { style: { position: 'relative' } },
      _react2.default.createElement(_Button2.default, {
        bem: { shale: !0 },
        className: _styleModule2.default['APILog-copy'],
        onClick: function onClick(e) {
          return copyHandler(e, curl);
        },
        size: 'sm',
        text: 'Copy'
      }),
      _react2.default.createElement(
        'pre',
        null,
        curl
      )
    ),
    _react2.default.createElement(
      _Title2.default,
      { level: 5 },
      'Headers'
    ),
    _react2.default.createElement(
      'div',
      null,
      headers.length > 0 && _react2.default.createElement(_Table2.default, { body: headers, pick: ['name', 'value'] }),
      !allHeaders.length || _react2.default.createElement(
        _ShowMore2.default,
        {
          height: '8em',
          label: _react2.default.createElement(ToggleHeaders, { text: 'All...' }),
          labelClose: _react2.default.createElement(ToggleHeaders, { text: 'Less...', theme: 'shale_ghost' })
        },
        _react2.default.createElement(_Table2.default, { body: allHeaders, pick: ['name', 'value'] })
      )
    ),
    query.length && _react2.default.createElement(
      _react2.default.Fragment,
      null,
      _react2.default.createElement(
        _Title2.default,
        { level: 5 },
        'Query Parameters'
      ),
      _react2.default.createElement(_Table2.default, { body: query, pick: ['name', 'value'] })
    ) || ''
  );
};
APILogRequest.propTypes = process.env.NODE_ENV !== "production" ? {
  allHeaders: _propTypes2.default.array,
  curl: _propTypes2.default.string,
  headers: _propTypes2.default.array,
  query: _propTypes2.default.array
} : {};

var APILogResponse = function APILogResponse(_ref7) {
  var _ref7$headers = _ref7.headers,
      headers = _ref7$headers === undefined ? [] : _ref7$headers,
      _ref7$allHeaders = _ref7.allHeaders,
      allHeaders = _ref7$allHeaders === undefined ? [] : _ref7$allHeaders,
      json = _ref7.json;

  var body = JSON.stringify(JSON.parse(json), null, 2);

  headers.forEach(WrapValuesInCode);
  allHeaders.forEach(WrapValuesInCode);

  return _react2.default.createElement(
    _react2.default.Fragment,
    null,
    _react2.default.createElement(
      _Title2.default,
      { level: 5 },
      'Body'
    ),
    _react2.default.createElement(
      'div',
      { style: { position: 'relative' } },
      _react2.default.createElement(_Button2.default, {
        bem: { shale: !0 },
        className: _styleModule2.default['APILog-copy'],
        onClick: function onClick(e) {
          return copyHandler(e, body);
        },
        size: 'sm',
        text: 'Copy'
      }),
      _react2.default.createElement(
        'pre',
        null,
        body
      )
    ),
    _react2.default.createElement(
      _Title2.default,
      { level: 5 },
      'Headers'
    ),
    _react2.default.createElement(
      'div',
      null,
      /* istanbul ignore next */!headers.length || _react2.default.createElement(_Table2.default, { body: headers, pick: ['name', 'value'] }),
      !allHeaders.length || _react2.default.createElement(
        _ShowMore2.default,
        {
          height: '8em',
          label: _react2.default.createElement(ToggleHeaders, { text: 'All...', theme: 'shale_ghost' }),
          labelClose: _react2.default.createElement(ToggleHeaders, { text: 'Less...' })
        },
        _react2.default.createElement(_Table2.default, { body: allHeaders, pick: ['name', 'value'] })
      )
    )
  );
};
APILogResponse.propTypes = process.env.NODE_ENV !== "production" ? {
  allHeaders: _propTypes2.default.array,
  headers: _propTypes2.default.array,
  json: _propTypes2.default.string
} : {};

var APILog = function (_React$Component) {
  _inherits(APILog, _React$Component);

  function APILog(props) {
    _classCallCheck(this, APILog);

    var _this = _possibleConstructorReturn(this, _React$Component.call(this, props));

    _this.curl = props.log.curl || 'No cURL available.';
    return _this;
  }

  APILog.prototype.render = function render() {
    var _props = this.props,
        log = _props.log,
        link = _props.link;
    var status = log.status,
        _log$startedDateTime = log.startedDateTime,
        startedDateTime = _log$startedDateTime === undefined ? '' : _log$startedDateTime,
        requestHeaders = log.requestHeaders,
        queryString = log.queryString,
        method = log.method,
        url = log.url;

    return _react2.default.createElement(
      _Flex2.default,
      { align: 'stretch', className: _styleModule2.default.APILog, layout: 'col', style: this.props.style },
      _react2.default.createElement(
        _Flex2.default,
        { align: 'center', className: _styleModule2.default['APILog-info'] },
        _react2.default.createElement(APILogInfo, { link: link, method: method, startedDateTime: startedDateTime, status: status, url: url })
      ),
      _react2.default.createElement(
        _Tabs2.default,
        { className: { root: 'Flex_inner', tabs: _styleModule2.default['APILog-tabs'] } },
        _react2.default.createElement(
          'div',
          { label: 'Request' },
          _react2.default.createElement(APILogRequest, {
            allHeaders: log.fullReqHeaders,
            curl: this.curl,
            headers: requestHeaders,
            query: queryString
          })
        ),
        _react2.default.createElement(
          'div',
          { label: 'Response' },
          _react2.default.createElement(APILogResponse, {
            allHeaders: log.fullResHeaders,
            headers: log.responseHeaders,
            json: log.responseBody.text
          })
        )
      )
    );
  };

  return APILog;
}(_react2.default.Component);

APILog.propTypes = process.env.NODE_ENV !== "production" ? {
  link: _propTypes2.default.string,
  log: _propTypes2.default.shape({
    curl: _propTypes2.default.string,
    fullReqHeaders: _propTypes2.default.array,
    fullResHeaders: _propTypes2.default.array,
    method: _propTypes2.default.oneOfType([_propTypes2.default.number, _propTypes2.default.string]),
    queryString: _propTypes2.default.array,
    requestHeaders: _propTypes2.default.array,
    response: _propTypes2.default.object,
    responseBody: _propTypes2.default.object,
    responseHeaders: _propTypes2.default.array,
    startedDateTime: _propTypes2.default.string,
    status: _propTypes2.default.oneOfType([_propTypes2.default.number, _propTypes2.default.string]),
    url: _propTypes2.default.string
  })
} : {};
exports.default = APILog;
module.exports = exports['default'];