import { useState, useEffect } from 'react';

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

function useReadmeApi(baseUrl) {
  const [pendingRequest, setPendingRequest] = useState(false);
  const [request, initRequest] = useState(null);
  const [response, setResponse] = useState({});
  const [error, setError] = useState(null);

  useEffect(() => {
    if (request) {
      fetchWrapper(baseUrl, request)
        .then(json => {
          setPendingRequest(!!json.success);
          setResponse(json);
        })
        .catch(({ message }) => {
          setError(message);
        });
    }
  }, [request]);

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

export default useReadmeApi;
