import 'whatwg-fetch';
import { validTokenPresent } from './checkAuth'
import { take, fork, cancel, call, put, cancelled, select } from 'redux-saga/effects'

function parseJSON(response) {
  return response.json();
}


function checkStatus(response) {
  if (response.status >= 200 && response.status < 300) {
    return response;
  }
  return parseJSON(response)
    .then(parsedResponse => {
      console.log(parsedResponse);
      const error = new Error(parsedResponse.error);
      error.statusText = response.statusText;
      throw error;
    });
}

export default function request(url, options) {
  return fetch(url, options)
    .then(checkStatus)
    .then(parseJSON);
}

export function* requestSaga(method, url, data) {
  const headers = {
    'Content-Type': 'application/json'
  };
  const options = {
    method: method,
    headers: headers
  };
  // retrieve token and set it if present
  const token = validTokenPresent();
    if (token) headers['x-access-token'] = token;

  if (data) options.body = JSON.stringify(data);

  return yield call(request, url, options);
}