export default function extractResponseErrorMessage(response) {
  if (!response) {
    return null;
  }

  // Handle Ember Data error response

  let { responseJSON, status } = response;

  if (responseJSON &&
      isErrorStatus(status) &&
      responseJSON.message) {
    return responseJSON.message;
  }

  // Handle ProgressEvent error response

  let { target } = response;

  if (target &&
      isErrorStatus(target.status) &&
      target.responseText) {

    let message;

    try {
      message = JSON.parse(target.responseText).message;
    } catch (e) {
      // Handle 413 status code. nginx returns HTML in responseText
      // instead of JSON, so the statusText is returned instead.
      if (target.statusText && target.status === 413) {
        message = target.statusText;
      } else {
        message = target.responseText;
      }
    }

    return message;
  }

  // Handle plain response error without known message format

  if (isErrorStatus(status)) {
    return `Server error: ${status}`;
  }

  return null;
}

function isErrorStatus(status) {
  return typeof status === 'number' &&
         status < 600 &&
         status >= 400;
}
