import _regeneratorRuntime from 'babel-runtime/regenerator';

var _this = this;

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

import classes from './style.module.scss';

import React from 'react';
import PropTypes from 'prop-types';
import copy from 'clipboard-copy';

import Flex from '../../components/Flex';
import Tabs from '../../components/Tabs';
import Table from '../../components/Table';
import Title from '../../components/Title';
import Button from '../../components/Button';
import HTTPStatus from '../../components/HTTPStatus';
import ShowMore from '../../components/ShowMore';

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

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

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

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

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

  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 React.createElement(
    Flex,
    { layout: 'row' },
    React.createElement(
      'small',
      null,
      React.createElement(
        Button,
        { bem: (_ref4 = {}, _ref4[theme] = true, _ref4), size: 'sm' },
        text
      )
    )
  );
};
ToggleHeaders.propTypes = process.env.NODE_ENV !== "production" ? { text: PropTypes.string, theme: PropTypes.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 React.createElement(
    React.Fragment,
    null,
    React.createElement(
      'div',
      { shift: 'end', style: { overflow: 'hidden', textOverflow: 'ellipsis' } },
      React.createElement(
        'b',
        null,
        React.createElement(HTTPStatus, { status: status }),
        ' ',
        React.createElement(
          'code',
          null,
          method
        )
      ),
      ' ',
      React.createElement(
        'code',
        null,
        url
      ),
      ' '
    ),
    !datetime || React.createElement(
      'span',
      { style: { opacity: 0.75, textAlign: 'right' } },
      datetime.toLocaleDateString('en-US', { dateStyle: 'short' }),
      ', ',
      datetime.toLocaleTimeString('en-US', { timeStyle: 'short' }).replace(' ', '')
    ),
    !link || React.createElement(
      'a',
      { href: link, rel: 'noopener noreferrer', style: { whiteSpace: 'nowrap' }, target: '_blank' },
      React.createElement(
        'b',
        null,
        'View Docs'
      )
    )
  );
};
APILogInfo.propTypes = process.env.NODE_ENV !== "production" ? {
  link: PropTypes.string,
  method: PropTypes.string,
  startedDateTime: PropTypes.string,
  status: PropTypes.oneOfType([PropTypes.number, PropTypes.string]),
  url: PropTypes.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 React.createElement(
    React.Fragment,
    null,
    React.createElement(
      Title,
      { level: 5 },
      'Body'
    ),
    React.createElement(
      'div',
      { style: { position: 'relative' } },
      React.createElement(Button, {
        bem: { shale: !0 },
        className: classes['APILog-copy'],
        onClick: function onClick(e) {
          return copyHandler(e, curl);
        },
        size: 'sm',
        text: 'Copy'
      }),
      React.createElement(
        'pre',
        null,
        curl
      )
    ),
    React.createElement(
      Title,
      { level: 5 },
      'Headers'
    ),
    React.createElement(
      'div',
      null,
      headers.length > 0 && React.createElement(Table, { body: headers, pick: ['name', 'value'] }),
      !allHeaders.length || React.createElement(
        ShowMore,
        {
          height: '8em',
          label: React.createElement(ToggleHeaders, { text: 'All...' }),
          labelClose: React.createElement(ToggleHeaders, { text: 'Less...', theme: 'shale_ghost' })
        },
        React.createElement(Table, { body: allHeaders, pick: ['name', 'value'] })
      )
    ),
    query.length && React.createElement(
      React.Fragment,
      null,
      React.createElement(
        Title,
        { level: 5 },
        'Query Parameters'
      ),
      React.createElement(Table, { body: query, pick: ['name', 'value'] })
    ) || ''
  );
};
APILogRequest.propTypes = process.env.NODE_ENV !== "production" ? {
  allHeaders: PropTypes.array,
  curl: PropTypes.string,
  headers: PropTypes.array,
  query: PropTypes.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 React.createElement(
    React.Fragment,
    null,
    React.createElement(
      Title,
      { level: 5 },
      'Body'
    ),
    React.createElement(
      'div',
      { style: { position: 'relative' } },
      React.createElement(Button, {
        bem: { shale: !0 },
        className: classes['APILog-copy'],
        onClick: function onClick(e) {
          return copyHandler(e, body);
        },
        size: 'sm',
        text: 'Copy'
      }),
      React.createElement(
        'pre',
        null,
        body
      )
    ),
    React.createElement(
      Title,
      { level: 5 },
      'Headers'
    ),
    React.createElement(
      'div',
      null,
      /* istanbul ignore next */!headers.length || React.createElement(Table, { body: headers, pick: ['name', 'value'] }),
      !allHeaders.length || React.createElement(
        ShowMore,
        {
          height: '8em',
          label: React.createElement(ToggleHeaders, { text: 'All...', theme: 'shale_ghost' }),
          labelClose: React.createElement(ToggleHeaders, { text: 'Less...' })
        },
        React.createElement(Table, { body: allHeaders, pick: ['name', 'value'] })
      )
    )
  );
};
APILogResponse.propTypes = process.env.NODE_ENV !== "production" ? {
  allHeaders: PropTypes.array,
  headers: PropTypes.array,
  json: PropTypes.string
} : {};

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

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

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

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

  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 React.createElement(
      Flex,
      { align: 'stretch', className: classes.APILog, layout: 'col', style: this.props.style },
      React.createElement(
        Flex,
        { align: 'center', className: classes['APILog-info'] },
        React.createElement(APILogInfo, { link: link, method: method, startedDateTime: startedDateTime, status: status, url: url })
      ),
      React.createElement(
        Tabs,
        { className: { root: 'Flex_inner', tabs: classes['APILog-tabs'] } },
        React.createElement(
          'div',
          { label: 'Request' },
          React.createElement(APILogRequest, {
            allHeaders: log.fullReqHeaders,
            curl: this.curl,
            headers: requestHeaders,
            query: queryString
          })
        ),
        React.createElement(
          'div',
          { label: 'Response' },
          React.createElement(APILogResponse, {
            allHeaders: log.fullResHeaders,
            headers: log.responseHeaders,
            json: log.responseBody.text
          })
        )
      )
    );
  };

  return APILog;
}(React.Component);

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


export default APILog;