'use strict';

exports.__esModule = true;

var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

var _react = require('react');

function _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; }

function fetchWrapper(baseUrl, _ref) {
  var path = _ref.path,
      headers = _ref.headers,
      options = _objectWithoutProperties(_ref, ['path', 'headers']);

  return fetch(baseUrl + '/' + path, _extends({}, options, {
    headers: _extends({
      'Content-Type': 'application/json'
    }, headers)
  })).then(function (response) {
    if (response.ok) return response.json();
    return response.text().then(function (err) {
      throw new Error(err);
    });
  });
}

function useReadmeApi(baseUrl) {
  var _useState = (0, _react.useState)(false),
      pendingRequest = _useState[0],
      setPendingRequest = _useState[1];

  var _useState2 = (0, _react.useState)(null),
      request = _useState2[0],
      initRequest = _useState2[1];

  var _useState3 = (0, _react.useState)({}),
      response = _useState3[0],
      setResponse = _useState3[1];

  var _useState4 = (0, _react.useState)(null),
      error = _useState4[0],
      setError = _useState4[1];

  (0, _react.useEffect)(function () {
    if (request) {
      fetchWrapper(baseUrl, request).then(function (json) {
        setPendingRequest(!!json.success);
        setResponse(json);
      }).catch(function (_ref2) {
        var message = _ref2.message;

        setError(message);
      });
    }
  }, [request]);

  return { response: response, error: error, setError: setError, pendingRequest: pendingRequest, initRequest: initRequest };
}

exports.default = useReadmeApi;
module.exports = exports['default'];