import fetch from 'node-fetch';

const BASE_URL = 'http://scoring-dev.madbean.ovh';
const PATH = '/scores';

const getJSONFromRelativeURL = relativeURL => fetch(`${BASE_URL}${relativeURL}`)
  .then(res => res.json());

const getEntities = () => getJSONFromRelativeURL(PATH)
  .then(json => json.data.scores);

const getEntityByURL = relativeURL => getJSONFromRelativeURL(relativeURL)
  .then(json => json.data.score);

const getEntity = id => getEntityByURL(`${PATH}/${id}`);

const addEntity = (score) => {
  const options = {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      Accept: 'application/json',
    },
    body: JSON.stringify(score),
  };

  fetch(`${BASE_URL}${PATH}`, options)
    .then(response => response.json())
    .then(json => json)
    .catch(console.log);
};

const updateEntity = (score) => {
  const options = {
    method: 'PUT',
    headers: {
      'Content-Type': 'application/json',
      Accept: 'application/json',
    },
    body: JSON.stringify(score),
  };

  fetch(`${BASE_URL}${PATH}/${score.ID}`, options)
    .then(response => response.json())
    .then(json => json)
    .catch(console.log);
};

export default {
  updateEntity,
  addEntity,
  getEntity,
  getEntities,
  PATH,
  getEntityByURL,
};
