import { connect } from 'react-refetch';
import { parse } from 'csv';

var csvConnector = connect.defaults({
  handleResponse: function handleResponse(response) {
    if (response.headers.get('content-length') === '0' || response.status === 204) {
      return;
    }

    var csv = response.text();

    if (response.status >= 200 && response.status < 300) {
      return csv.then(function (text) {
        return new Promise(function (resolve, reject) {
          parse(text, function (err, data) {
            if (err) {
              reject(err);
            }
            resolve(data);
          });
        });
      });
    } else {
      return csv.then(function (cause) {
        return Promise.reject(new Error(cause));
      });
    }
  }
});

csvConnector(function (props) {
  return {
    userFetch: '/users/' + props.userId + '.csv'
  };
})(Profile);