export function ajaxPopup(path, title, divCode, divLibelle, params, width_popup, reload = false) {
    if(path == null)
        throw 'Invalid path';
    activeLoader();
    var post = {'divCode' : divCode, 'divLibelle' : divLibelle};
    post = $.extend( post, params );
    
    $.ajax({
        dataType: 'html',
        url: path,
        data: post,
        type: "POST",
        statusCode: {
            413: function(xhr) {
                desactiveLoader();
                desactivePopup();
                alert('Error - ModSecurity.');
            },
            500: function(xhr) {
                desactiveLoader();
                desactivePopup();
                alert('Internal Server Error.');
            }
        },
        success: function(result, textStatus, request){            

            // Case : json popup
            if (request.getResponseHeader('Content-Type') == 'application/json') {
                let data = JSON.parse(result);

                if (data.action != undefined) {
                    window.action[ data.action ]( request, null );
                    return;
                }

                window.action.successFormPopup(data, textStatus, request);
                desactiveLoader();
                return;
            }

            if(width_popup == null || width_popup == '' )
                width_popup = 'modal_small';
            
            $("#modal-content").removeClass('modal_large modal_small');
            
            activePopup(title, result, width_popup, reload);

            desactiveLoader();
        },
        error: function (xhr) {
            // Assume http 400 -> show constraint validation error
            desactiveLoader();
            activePopup(
                'Erreur validation', // TODO : translate
                xhr.responseText,
                'modal_small',
                reload
            );
        }
    });
}

/** FONCTION POPUP ERREUR **/
/**
 * @TODO : can be replaced ?
 */
export function activePopupErreur(path, titre, value, urlErreur, params, enteteTableau, pathArret) { 
    
    activeLoader();
    if(params==null){
        params='';
    }
    if(enteteTableau==null){
        enteteTableau='';
    }
    if(pathArret==null){
        pathArret='';
    }

    $( document ).ready(function() {
        $.ajax({
            url: path,
            data: {'Erreur' : value, 'Path' : urlErreur, 'params' : params, 'enteteTableau' : enteteTableau, 'pathArret': pathArret},
            type: "POST",
            success: function(result){
                desactiveLoader();
                document.getElementById('modal-content').classList.add('modal_small');
                document.getElementById('modal-title').innerHTML = titre;
                // TODO : remove script tag from ajax and use ``document.getElementById('modal-body').innerHTML = result;``
                $('#modal-body').html(result);
                activePopup();  
                $('.modal-header').addClass('popup_error');  
            }
        });	
    });
}


/** FONCTION POPUP ERREUR **/
export function activePopupInformation(path, titre, value, urlErreur, params, enteteTableau, pathArret, message) { 
    
    activeLoader();
    if(params==null){
        params='';
    }
    if(enteteTableau==null){
        enteteTableau='';
    }
    if(pathArret==null){
        pathArret='';
    }

    $( document ).ready(function() {
        $.ajax({
            url: path,
            data: {'Erreur' : value, 'Path' : urlErreur, 'params' : params, 'enteteTableau' : enteteTableau, 'pathArret': pathArret, 'message' : message},
            type: "POST",
            success: function(result){
                desactiveLoader();
                $("#modal-content").addClass("modal_small");
                $("#modal-title").html(titre);
                $("#modal-body").html(result);
                activePopup();
            }
        });
    });
    
}


/* Popup de confirmation */
export function ajaxValidationPopupRedirect(path, form)
{
    activeLoader();
    $.ajax({
        url : path ,
        type: 'POST',
        data: $('#'+form).serialize(),
        success: function (data) {            
                desactiveLoader();
                $("#modal-content").addClass("modal_small");
                $("#modal-body").html(data);
                $("#modal-title").html('Erreur validation');
                activePopup();
        },
        error: function (data){
            data = jQuery.parseJSON(data.responseText);
            window.location.href = data.path;
        }
    });
};

 
/**
 * ID -> Entity ou Reload selon le controller qui suivra
 * **/
export function popupConfirmation(path, id, URL, message, div, option, loader, popup, form, onclick, refresh, div_refresh, form_refresh, iconePopup, title, withOutPopup, reload)
{
    desactivePopup();
    activeLoader();
    if(div == undefined)
        div = "content_tableau";
    
    $( document ).ready(function() {
        $.ajax({
            dataType : 'html',
            url: path,
            data: {'Path' : URL , 'Message' : message, 'Entity' : id, 'div' : div, 'option' : option, 'loader' : loader, 'popup' : popup, 'form' : form, 'onclick' : onclick, 'refresh' : refresh, 'div_refresh' : div_refresh, 'form_refresh' : form_refresh, 'iconePopup' : iconePopup, 'withOutPopup' : withOutPopup, 'reload' : reload},
            type: "POST",
            success: function(result){      
                desactiveLoader();
                $("#modal-content").addClass("modal_small");
                $("#modal-title").html(title);
                $("#modal-body").html(result);
                activePopup ();
            }
        });
    });
}


export function ajaxPopupV2(path,idForm, title)
{
    let form = null;
    if (idForm) {
        form = $('#'+idForm).serialize();
    } else {
        form = {};
    }
    activeLoader();
    $.ajax({
        url: path,
        type: 'POST',
        dataType: 'html',
        data: form,
        statusCode: {
            413: function(xhr) {
                desactiveLoader();
                desactivePopup();
                alert('Error - ModSecurity.');
            }
        },
        success: function (data) {
            desactiveLoader();
            $("#modal-content").addClass("modal_small");
            $("#modal-body").html(data);
            $("#modal-title").html(title);

            activePopup();
        },
        error: function (data){

            data = jQuery.parseJSON(data.responseText);
            if (data.status == '500') {
                desactiveLoader();
                desactivePopup();
                alert('Internal Server Error.');
            } else {
                // window.location.href = data.path;
                if (data.action == 'close') {
                    desactivePopup();
                    desactiveLoader();
                } else {
                    redirectJSWithPost(data.path , data.post);				
                }
            }
        }
    });
}

export function ajaxPopupJSON(path,idForm)
{
    activeLoader();
    $.ajax({
        dataType : 'html',
        url: path,
        type: "POST",
        data: $('#'+idForm).serialize(),
        statusCode: {
            413: function(xhr) {
                desactiveLoader();
                desactivePopup();
                alert('Error - ModSecurity.');
            }
        },
        success: function(result){
            var data = jQuery.parseJSON(result);
            
            if(data.statut == 'O')
            {
                redirectJSWithPost(data.path, data.post);
            }
            else
            {
                desactiveLoader();
                $("#modal-content").addClass("modal_small");
                $("#modal-body").html(data.content);
                activePopup();
            }
        }
    });	
}
