const transformCfg = function(cfg) {
  return {
    ...cfg,
    headers: {
      '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);
      const xhr = new XMLHttpRequest();
      cfg = transformCfg(cfg || {});
      cfg.url = url;
      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{
      const xhr = new XMLHttpRequest();
      cfg = transformCfg(cfg || {});
      cfg.url = url;
      xhr.open("GET", url, true);
      xhrProceed(xhr, url, cb);
      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)
    });
  }
};