{# @copyright   Copyright (C) 2010-2024 Combodo SAS #}
{# @license     http://opensource.org/licenses/AGPL-3.0 #}

// for each row action...
{% for aAction in oUIBlock.GetRowActions() %}


    // register action buttons click
    $('body').on('click', 'button[data-table-id="{{ oUIBlock.GetId() }}"][data-action-id="{{ loop.index0 }}"]', function() {

        // variables accessible from action row js
        let oDatatable = $('#{{ oUIBlock.GetId() }}').DataTable();
        let oTrElement = $(this).closest('tr');
        let sLabel = $(this).data('label');
        let iActionId = $(this).data('action-id');
        let aRowData = oDatatable.row(oTrElement).data();
        let sConfirmButtonClass = 'ibo-is-primary';

        {% if aAction.confirmation.confirm_button_class is not empty %}
            sConfirmButtonClass = '{{ aAction.confirmation.confirm_button_class }}';
        {% endif %}

        {% if aAction.confirmation is defined %}

            // Prepare confirmation title
            let sTitle = `{{ 'UI:Datatables:RowActions:ConfirmationDialog'|dict_s|escape('js') }}`;
            {% if aAction.confirmation.title is defined %}
                sTitle = `{{ aAction.confirmation.title|dict_s|escape('js') }}`;
            {% endif %}
            sTitle = sTitle.replaceAll('{item}', aRowData['{{ aAction.confirmation.row_data }}']);

            // Prepare confirmation message
            let sMessage = `{{ 'UI:Datatables:RowActions:ConfirmationMessage'|dict_s|escape('js') }}`;
            {% if aAction.confirmation.message is defined %}
                sMessage = `{{ aAction.confirmation.message|dict_s|escape('js') }}`;
            {% endif %}
            sMessage = sMessage.replaceAll('{item}', aRowData['{{ aAction.confirmation.row_data }}']);

            // Handle action row with confirmation modal
            CombodoModal.OpenConfirmationModal({
                title: sTitle,
                content: sMessage,
                callback_on_confirm: ActionRowFunction{{ oUIBlock.GetId() }}{{ loop.index0 }},
                buttons: {
                    confirm: {
                        text: sLabel,
                        classes: [sConfirmButtonClass]
                    }
                },
                {% if aAction.confirmation.do_not_show_again_pref_key is defined %}
                do_not_show_again_pref_key: '{{ aAction.confirmation.do_not_show_again_pref_key }}',
                {% endif %}
            }, [oDatatable, oTrElement, iActionId, aRowData]);

        {% else %}

            // Handle action row without confirmation
            ActionRowFunction{{ oUIBlock.GetId() }}{{ loop.index0 }}(oDatatable, oTrElement, iActionId, aRowData);

        {% endif %}

    });

    // action row function declaration
    function ActionRowFunction{{ oUIBlock.GetId() }}{{ loop.index0 }}(oDatatable, oTrElement, iActionId, aRowData){
        {{ aAction.js_row_action|raw }};
        return true;
    }

{% endfor %}
