import 'isomorphic-fetch';

export const fetchRecipe = (recipeID, callback) => {
  fetch(`http://localhost:8080/api/v1/recipes/${recipeID}`, {
    method: 'GET',
    headers: {
      Accept: 'application/json',
      'Content-Type': 'application/json',
    },
    credentials: 'same-origin',
  })
  .then((response) => {
    if (response.status >= 400) {
      throw new Error('Bad response from server');
    }
    return response.json();
  })
  .then((data) => {
    callback(data);
  })
  .catch((error) => {
    console.log('Error:', error);
    return;
  });
};

const assignAuthorToNewRecipe = (author, recipe) => {
  const recipeCopy = {};
  Object.keys(recipe).forEach((k) => {
    if (k !== 'id' && k !== 'created_at' && k !== 'updated_at') {
      recipeCopy[k] = recipe[k];
    }
  });
  recipeCopy.parent = recipe.id;
  recipeCopy.author = author;
  return recipeCopy;
};

const bindAuthorToNewRecipe = (author) => assignAuthorToNewRecipe.bind(null, author);

export const createRecipe = (recipe, callback) => {
  fetch('http://localhost:8080/api/v1/recipes/', {
    method: 'POST',
    headers: {
      Accept: 'application/json',
      'Content-Type': 'application/json',
    },
    credentials: 'same-origin',
    body: JSON.stringify(recipe),
  })
  .then((response) => {
    if (response.status >= 400) {
      callback(new Error('Bad response from server'));
    }
    return response.json();
  })
  .then((data) => {
    callback(data);
  })
  .catch((error) => {
    console.log('Error:', error);
    return;
  });
};

export const forkRecipe = (originalRecipeID, userID, callback) => {
  fetchRecipe(originalRecipeID, (recipe) => {
    createRecipe(bindAuthorToNewRecipe(userID)(recipe), callback);
  });
};

export const fetchUser = (callback) => {
  fetch('http://localhost:8080/api/v1/user/', {
    credentials: 'same-origin',
  })
  .then((response) => {
    if (response.status >= 400) {
      throw new Error('Bad response from server');
    }
    return response.json();
  })
  .then((data) => {
    callback(data);
  })
  .catch((error) => {
    console.log('Error:', error);
    return;
  });
}

@@ -2116,10 +2116,576 @@
 ;%0A  %7D);%0A
+%7D;%0A%0Aexport const fetchRecipes = (recipeIDList, callback) =%3E %7B%0A  const formattedQuery = JSON.stringify(recipeIDList).replace('%5B','%7B').replace('%5D','%7D');%0A  // console.log(formattedQuery);%0A  fetch(%60http://localhost:8080/api/v1/recipes/?recipes=$%7BformattedQuery%7D%60, %7B%0A    credentials: 'same-origin',%0A  %7D)%0A  .then((response) =%3E %7B%0A    if (response.status %3E= 400) %7B%0A      throw new Error('Bad response from server');%0A    %7D%0A    return response.json();%0A  %7D)%0A  .then((data) =%3E %7B%0A    callback(data);%0A  %7D)%0A  .catch((error) =%3E %7B%0A    console.log('Error:', error);%0A    return;%0A  %7D);%0A
 %7D%0A

Add utility function for getting multiple recipes