var ajax_error_popup = function (reponse,status,msg = "") {


    if( ("responseJSON" in reponse)){
        status = reponse.status; // 500
        let jqXHRJSON = reponse.responseJSON;
        console.log(jqXHRJSON);
        if(!$.isEmptyObject(jqXHRJSON)){
            reponse = jqXHRJSON;
        }
    }

    //var message = (navigator.onLine) ? msg:'{{__("Vous n'êtes pas connecté à internet.")}}';
    var message =  '{{__("Une erreur imprévue est survenue lors de la demande")}}.'+
        '<br><center> <marquee class="text-danger">'+msg+'</marquee></center>';
    var config = {
        icon: 'error',
        //allowOutsideClick:false,
        title: "Oops...",
        html: message,
        footer: "",
    };
    serverStatus.get(); // fetch all server status
    let statuts_errors = serverStatus.status;

    console.log("status error = "+status,reponse);
    console.log("rep url  = "+reponse.url);

    if( $.inArray(status,statuts_errors) !== -1 ){
        let notif = reponse.notification;
        config.html = notif.msg;
        config.title = notif.title;
        config.icon = 'warning';

        if(reponse.url !== ""){
            if( status === statuts_errors[0] ){
                config.footer = '<span class="text-danger">' +
                    '<a style="text-decoration:underline;" class="text-success" href="'+reponse.url+'">'+
                    'Cliquez ici '+
                    '</a> '+"pour vous connecté."+
                    ' </span>'
            }
        }
        if(status === statuts_errors[0]){
            reponse.url = document.URL;
        }
    }
    else{
        reponse.url = "";
    }
    swal.fire(config)
        .then( result => {
            if (result.isConfirmed) {
                if(reponse.url !== ""){
                    location.href = reponse.url;
                }
            }
        })

};


var fetch_async = async function(url, param = {}, swal = true) {
    let csrf_token = $('meta[name="csrf-token"]').attr('content');
    //let csrf_token = document.querySelector('meta[name="csrf-token"]');
    if(!("headers" in param)){
        param.headers =  {
            'X-CSRF-TOKEN': csrf_token,
            //'Accept': 'application/json , text/plain, */*',
            'Content-Type': 'application/json , multipart/form-data',
            'X-Requested-With': 'XMLHttpRequest',
        };
    }else{
        param['headers']['X-CSRF-TOKEN'] = csrf_token;
        param['headers']['X-Requested-With'] = "XMLHttpRequest";
    }

    if(!("method" in param)){
        param.method = 'get';
    }

    if( ("body" in param)){
        if(param.method === 'get'){
            url = url+'?';
            $.each(param.body , function (index, value){
                let v = index+"="+value+"&";
                if(typeof value === 'object'){
                    v = "";
                    $.each(value ,function(i, d){
                        //v += index+"["+i+"]="+d+"&";
                        v += index+"[]="+d+"&";
                    });
                }
                url += v;
            }); // get n'a pas besoin de 'body'
            delete param.body;
        }else{ // post
            param.body = JSON.stringify(param.body);
        }
    }

    return  await  fetch(url,param)
                   .then(response => {
                        let result = response.json();
                        let status = response.status;
                        let msg = result.statusText;
                        if (!response.ok) {
                            if(swal){
                                result.then(data => {
                                    ajax_error_popup(data,status,msg);
                                });
                            }
                            throw new Error(msg);
                        }
                        return result;
                    });
};

var changeStatutCommande = function () {
    let key = "url_change_statut_cmd";
    let url = localStorage.getItem(key);
    if (url !== ""){
        fetch_async(url)
        .then( reponse => {
          console.log(JSON.stringify(reponse));
        });
    }
    localStorage.removeItem(key);
};

