const transformCfg = function(cfg) {
  return Object.assign({}, cfg, {
    headers: Object.assign(
      {'Content-Type': 'application/json'},
      cfg && cfg.headers || {}
    )
  });
};
const xhrProceed = function(method, xhr, cfg, cb) {
  xhr.open(method, cfg.url, true);
  for(let key in cfg.headers){
    xhr.setRequestHeader(key, cfg.headers[key]);
  }

  xhr.onreadystatechange = function () {
    if (xhr.readyState === 4 && xhr.status === 200) {
      let json;
      try {
        json = JSON.parse(xhr.responseText);
        cb && cb(false, json);
      }catch (e) {
        console.error('AJAX:'+ method +' Incorrect Response ← '+cfg.url, xhr.responseText, e);
        cb && cb(true, e);
      }
    }else if(xhr.status === 404){
      cb && cb(true);
    }else if(xhr.status === 401){
      //Пользователь не авторизован
      window.location.href = "/login";
      return;
    }else if(xhr.status === 403){
      //Нет доступа к ассистенту
      window.location.href = "/";
      return;
    }else if (xhr.status >= 400){
      /*HeaderModel.statusNotification.statuses.push({type: 'error'});
      setTimeout(function () {
        HeaderModel.statusNotification.statuses.length = 0;
      }, 3000);*/
      cb && cb(true, {"status":"error"});
      return;
    }
  };
};
export const Ajax = {
  post(url, data, cb, cfg){
    let stringData='';
    try{
      stringData = JSON.stringify(data);
      cfg = transformCfg(cfg || {});
      cfg.url = url;

      const xhr = new XMLHttpRequest();
      xhrProceed("POST", xhr, cfg, cb);
      xhr.send(stringData);
    }catch (e) {
     /* HeaderModel.statusNotification.statuses.push({type: 'error'});
      setTimeout(function () {
        HeaderModel.statusNotification.statuses.length = 0;
      }, 3000);*/
      console.error('AJAX:POST → '+url, e);
      cb && cb(true, e);
    }
  },

  get(url, cb, cfg){
    try{
      cfg = transformCfg(cfg || {});
      cfg.url = url;
      const xhr = new XMLHttpRequest();
      xhrProceed("GET", xhr, cfg, cb);
      xhr.send(null);
    }catch (e) {
      /*HeaderModel.statusNotification.statuses.push({type: 'error'});
      setTimeout(function () {
        HeaderModel.statusNotification.statuses.length = 0;
      }, 3000);*/
      console.error('AJAX:GET → '+url, e);
      cb && cb(true, e);
    }
  }
};
export const AsyncAjax = {
  get(url, cfg) {
    return new Promise(function(resolve, reject) {
      Ajax.get(url, function(err, data) {
        if(err){
          reject(data);
        }else{
          resolve(data);
        }
      }, cfg)
    });
  },
  post(url, data, cfg){
    return new Promise(function(resolve, reject) {
      Ajax.post(url, data, function(err, data) {
        if(err){
          reject(data);
        }else{
          resolve(data);
        }
      }, cfg)
    });
  }
};