import Ember from 'ember';
import XHRError from './xhr-error';

const { get, isNone } = Ember;

export function getContext(router) {
  var infos = router.currentState.routerJsState.handlerInfos;

  var url = router.get('location').getURL().split("?")[0];
  var routeName = infos[infos.length - 1].name;

  var firstSegments = routeName.replace(".index", "").replace(/\./g, ' ');
  var prettyRouteName = Ember.String.capitalize(firstSegments);

  return prettyRouteName + " (" + routeName + ", " + url + ")";
}

export function generateError(cause, stack) {
  var error = new Error(cause);
  error.stack = stack;
  return error;
}

export function getError(error) {
  if (!error) {
    return new Error();
  }

  const resource = get(error, 'resource');
  let message;

  // Trace XHR JSON error.
  if (!isNone(message = get(error, 'responseJSON'))) {
    return new XHRError(resource, JSON.stringify(message));
  // Trace XHR Text error.
  } else if (!isNone(message = get(error, 'responseText'))) {
    return new XHRError(resource, message);
  // Trace XHR unknown error.
  } else if (!isNone(message = get(error, 'status'))) {
    const statusText = get(error, 'statusText');

    return new XHRError(resource, `status='${message}' statusText='${statusText}'`);
  // Trace JSON objects.
  } else if (typeof error === 'object') {
    try {
      message = JSON.stringify(error);

      return new Error(message);
    } catch(e) {
      // NOOP.
    }
  }

  return new Error(error);
}

@@ -128,19 +128,21 @@
 er) %7B%0A  
-var
+const
  infos =
@@ -190,22 +190,23 @@
 rInfos;%0A
-%0A
   
-var
+const
  url = r
@@ -246,19 +246,19 @@
 lit(
-%22?%22
+'?'
 )%5B0%5D;%0A  
 var 
@@ -253,19 +253,21 @@
 )%5B0%5D;%0A  
-var
+const
  routeNa
@@ -301,22 +301,23 @@
 %5D.name;%0A
-%0A
   
-var
+const
  firstSe
@@ -347,20 +347,20 @@
 ace(
-%22
+'
 .index
-%22, %22%22
+', ''
 ).re
@@ -380,19 +380,21 @@
 ' ');%0A  
-var
+const
  prettyR
@@ -454,16 +454,19 @@
  return 
+%60$%7B
 prettyRo
@@ -476,46 +476,33 @@
 Name
- + %22 (%22 + routeName + %22, %22 + url + %22)%22
+%7D ($%7BrouteName%7D, $%7Burl%7D)%60
 ;%0A%7D%0A
@@ -554,11 +554,13 @@
 %7B%0A  
-var
+const
  err
@@ -582,16 +582,17 @@
 cause);%0A
+%0A
   error.
@@ -606,16 +606,17 @@
  stack;%0A
+%0A
   return
@@ -705,16 +705,138 @@
 );%0A  %7D%0A%0A
+  // get jqXHR from rejection triggered by ember-http (RSVP promises).%0A  if (error.jqXHR) %7B%0A    error = error.jqXHR;%0A  %7D%0A%0A
   const 

implement ember-http with RSVP interface