import fetch from 'node-fetch';

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

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

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

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

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

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

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

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

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

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