import log = require("loglevel");
import { NotificationService } from "../../common/service/NotificationService";
import { Sprintf } from "../../common/global/Sprintf";
// import { sprintf } from "sprintf-js";
///<reference path="../SprintfTest.d.ts" />

// import sprintf = require('sprintf-js').sprintf;

export function fetchErrorHandler(response: Response, ns: NotificationService) {
  // alertify.success('Current position : ' + alertify.get('notifier', 'position'));
  if (!response.ok) {
    return response
      .text()
      .catch((err) => {
        // the status was not ok and there is no json body
        // throw new Error(response.statusText);
        // window.alert(sprintf('Some error occured. Http code is %s', response.status));
        ns.error(
          Sprintf("Some error occured. Http code is %s", response.status)
        );
        log.error(
          Sprintf("Some error occured. Http code is %s", response.status)
        );
        log.error();
        return true;
      })
      .then((json) => {
        // the status was not ok but there is a json body
        // throw new Error(json.error.message); // example error message returned by a REST API
        // window.alert(sprintf('Error: %s (Http code %s)', json, response.status));
        ns.error(
          Sprintf("Some error occured. Http code is %s", response.status)
        );
        log.error(
          Sprintf("Some error occured. Http code is %s", response.status)
        );
        log.error(json);
        return true;
      });
  }
}
