{#
    (C) 2020 - ntop.org

    This is the template for the endpoint recipients page. If there are no endpoints
    configured yet then show an alert to the user.
#}

<div class="row mb-5">
    <div class="col-md-12">
        <div class="card card-shadow">
            <div class="card-body">
                    <table class="table w-100 table-bordered table-striped table-hover my-3" id="recipient-list">
                        <thead>
                            <tr>
                                <th>{{ i18n('actions') }}</th>
                                <th>{{ i18n('endpoint_notifications.recipient_name') }}</th>
                                <th>{{ i18n('endpoint_notifications.type') }}</th>
                                <th>{{ i18n('endpoint_notifications.associated_to_endpoints') }}</th>
                                <th>{{ i18n('endpoint_notifications.time_since_last_use') }}</th>
                                <th>{{ i18n('endpoint_notifications.num_uses') }}</th>
                                <th>{{ i18n('endpoint_notifications.num_drops') }}</th>
				                <th>{{ i18n('endpoint_notifications.fill_pct') }}</th>
                                <th>{{ i18n('endpoint_notifications.notifications_type_abbr') }}</th>
                                <th>{{ i18n('endpoint_notifications.categories') }}</th>
                                <th>{{ i18n('endpoint_notifications.entities') }}</th>
                                <th>{{ i18n('endpoint_notifications.alerts') }}</th>
                                <th>{{ i18n('endpoint_notifications.min_severity') }}</th>
                                <th>{{ i18n('endpoint_notifications.silence_mul_alerts') }}</th>
                            </tr>
                        </thead>
                    </table>
            </div>
            <div class="card-footer">
                {* ui_utils.render_configuration_footer('notifications') *}
            </div>
        </div>
    </div>
</div>

{# Generate a template for each endpoint entry #}
{% for endpoint_key, endpoint in pairs(notifications.endpoints) do %}
    <template id="{{ endpoint_key }}-template">
        {* script_manager.renderNotificationTemplate(endpoint.recipient_template.script_key, endpoint.recipient_template.template_name) *}
    </template>
{% end %}

{* template_utils.gen("pages/modals/recipients_endpoint/add.template", notifications) *}
{* template_utils.gen("pages/modals/recipients_endpoint/remove.template", notifications) *}
{* template_utils.gen("pages/modals/recipients_endpoint/edit.template", notifications) *}
{* template_utils.gen("pages/modals/recipients_endpoint/users.template", notifications) *}

<script type="text/javascript">
    const CAN_CREATE_RECIPIENT = {{ notifications.can_create_recipient }};
    const endpointTypeFilters = {* json.encode(notifications.filters.endpoint_types) *};
    let pageCsrf = "{{ ntop.getRandomCSRFValue() }}";

    i18n_ext.warning ="{{ i18n('warning', {}) }}";
    i18n_ext.showing_x_to_y_rows = "{{ i18n('showing_x_to_y_rows', {x='_START_', y='_END_', tot='_TOTAL_'}) }}";
    i18n_ext.search = "{{ i18n('search') }}";
    i18n_ext.edit = "{{ i18n('edit') }}";
    i18n_ext.remove = "{{ i18n('remove') }}";
    i18n_ext.delete = "{{ i18n('delete') }}";
    i18n_ext.all = "{{ i18n('all') }}";
    i18n_ext.empty_template = "{{ i18n('endpoint_notifications.empty_template') }}";
    i18n_ext.createEndpointFirst = "{{ (#notifications.endpoint_list > 0 and '' or i18n('endpoint_notifications.create_endpoint_first')) }}";
    i18n_ext.testing_recipient = "{{ i18n('endpoint_notifications.testing_recipient') }}";
    i18n_ext.working_recipient = "{{ i18n('endpoint_notifications.working_recipient') }}";
    i18n_ext.timed_out = "{{ i18n('endpoint_notifications.timed_out') }}";
    i18n_ext.server_error = "{{ i18n('endpoint_notifications.server_error') }}";
    i18n_ext.endpoint_recipient_already_existing = "{{ i18n('endpoint_notifications.endpoint_recipient_already_existing') }}";
    i18n_ext.endpoint_type = "{{ i18n('endpoint_notifications.type') }}";
    i18n_ext.endpoint_types = {* json.encode(notifications.endpoint_types_labels) *};
    i18n_ext.pool_types = {* json.encode(i18n('pools.pool_name')) *};
    i18n_ext.endpoint_severities = {* json.encode(i18n('endpoint_notifications.severities')) *};
    i18n_ext.pools = "{{ i18n('endpoint_notifications.bind_to_num_pools') }}";
    i18n_ext.recipient = "{{ i18n('recipient') }}";

  const TABLE_DATA_REFRESH = 15000;
    const DEFAULT_RECIPIENT_ID = 0;
    const COLUMN_INDEX_ENDPOINT_TYPE = 1;
    const SEVERITIES = [
        'debug',
        'info',
        'notice',
        'warning',
        'error',
        'critical',
        'alert',
        'emergency'
    ];


    const getInvalidMessage = (formSelector, param) => {

        const $inputsTemplate = $(`${formSelector} .recipient-template-container [name]`);
        
        let localizedString = "";
        $inputsTemplate.each(function (i, input) {
            if ($(this).attr('name') == param) {
                localizedString = $(this).attr('data-validation-message');
            } 
        });
        return localizedString;
    }

    const makeFormData = (formSelector) => {

        const $inputsTemplate = $(`${formSelector} .recipient-template-container [name]`);

        const params = {
            recipient_name: $(`${formSelector} [name='recipient_name']`).val(),
            endpoint_id: $(`${formSelector} [name='endpoint']`).val(),
            recipient_host_pools: $(`${formSelector} [name='recipient_host_pools']`).val().join(","),
            recipient_am_hosts: $(`${formSelector} [name='recipient_am_hosts']`).val().join(","),
            recipient_silence_multiple_alerts: $(`${formSelector} [name='recipient_silence_alerts']`).is(':checked'),
            recipient_notifications_type: $(`${formSelector} [name='recipient_notifications_type']`).val()
        };

        if($(`${formSelector} [for='per_alerts_tab']`).hasClass('btn-primary') 
            || $(`${formSelector} [for='edit_per_alerts_tab']`).hasClass('btn-primary')) {
            params.recipient_checks = $(`${formSelector} [name='recipient_alerts']`).val().join(",");
        } else {
            params.recipient_minimum_severity = $(`${formSelector} [name='recipient_minimum_severity']`).val();
            params.recipient_check_categories = $(`${formSelector} [name='recipient_check_categories']`).val().join(",");
            params.recipient_check_entities = $(`${formSelector} [name='recipient_check_entities']`).val().join(",");
        }

        // load each recipient params inside the template container in params
        $inputsTemplate.each(function (i, input) {
            params[$(this).attr('name')] = $(this).val().trim();
        });

        return params;
    }

    const testRecipient = async (data, $button, $feedbackLabel) => {

        const body = { action: 'test', csrf: pageCsrf };
        $.extend(body, data);

        $button.attr("disabled", "disabled");
        $button.find('span.spinner-border').fadeIn();
        $feedbackLabel.removeClass(`alert-danger alert-success`).text(`${i18n_ext.testing_recipient}...`).show();

        try {

            const request = await NtopUtils.fetchWithTimeout(`${http_prefix}/lua/edit_notification_recipient.lua`, {
                method: 'post',
                body: JSON.stringify(body),
                headers: {
                    'Content-Type': 'application/json'
                }
            }, 5000);
            const { result } = await request.json();

            if (result.status === "failed") {
                $button.find('span.spinner-border').fadeOut(function () {
                    $feedbackLabel.addClass(`alert-danger`).html(result.error.message);
                });
                return;
            }

            // show a green label to alert the endpoint message
            $button.find('span.spinner-border').fadeOut(function () {
                $feedbackLabel.addClass('alert-success').html(i18n_ext.working_recipient).fadeOut(3000);
            });

        }
        catch (err) {

            $button.find('span.spinner-border').fadeOut(function () {

                $feedbackLabel.addClass(`alert-danger`);

                if (err.message == "Response timed out") {
                    $feedbackLabel.html(i18n_ext.timed_out);
                    return;
                }
                $feedbackLabel.html(i18n_ext.server_error);
            });
        }
        finally {
            $button.removeAttr("disabled");
        }

    }

    const createTemplateOnSelect = (formSelector) => {

        const $templateContainer = $(`${formSelector} .recipient-template-container`);
        // on Endpoint Selection load the right template to fill
        $(`${formSelector} select[name='endpoint']`).change(function (e) {
            const $option = $(this).find(`option[value='${$(this).val()}']`);
            const $cloned = cloneTemplate($option.data('endpointKey'));
            // show the template inside the modal container
            $templateContainer.hide().empty();
            if ($cloned) {
                $templateContainer.append($(`<hr>`));
                $templateContainer.append($cloned).show();
            }
            $(`${formSelector} span.test-feedback`).fadeOut();
        });
    }

    function cloneTemplate(type) {
        if(!type) return "";

        const template = $(`template#${type}-template`).html();
        // if the template is not empty then return a copy of the template content
        if (template.trim() != "") {
            const $template = $(template);
            return $template;
        }

        return (null);
    }

    let dtConfig = DataTableUtils.getStdDatatableConfig([
        {
            text: '<i class="fas fa-plus"></i>',
            className: 'btn-link',
            attr: {
                id: 'btn-add-recipient',
                disabled: $("#endpoint-select").children().length == 0
            },
            enabled: CAN_CREATE_RECIPIENT,
            action: function (e, dt, node, config) {
                $("#recipient-name-input").val("");
                $("#recipient-severity-select").val($("#recipient-severity-select option[value='5']").val());
                $("#endpoint-select").val($("#endpoint-select option:first").val());
                $("#recipient-template-container-add-id input").val("");
		$('#add-recipient-categories-select').selectpicker('selectAll');
		$('#add-recipient-categories-select').selectpicker('refresh');
		$('#add-recipient-entities-select').selectpicker('selectAll');
		$('#add-recipient-entities-select').selectpicker('refresh');
		$('#add-recipient-host-pools-select').selectpicker('selectAll');
		$('#add-recipient-host-pools-select').selectpicker('refresh');
		$('#add-recipient-am-hosts-select').selectpicker('selectAll');
		$('#add-recipient-am-hosts-select').selectpicker('refresh');
                $('#add-recipient-modal').modal('show');
            }
        },
        {
            text: '<i class="fas fa-sync"></i>',
            action: function (e, dt, node, config) {
                $recipientsTable.ajax.reload();
            }
        }
    ]);
    dtConfig = DataTableUtils.setAjaxConfig(dtConfig, `${http_prefix}/lua/get_recipients_endpoint.lua`);
    dtConfig = DataTableUtils.extendConfig(dtConfig, {
        columns: [
            {   
                responsivePriority: 1,
                targets: -1,
                className: 'text-center',
                data: null,
                render: function (_, type, recipient) {

                    if (!recipient.endpoint_conf) return '';

                    const isBuiltin = (recipient.endpoint_conf && recipient.endpoint_conf.builtin) || false;

                    return DataTableUtils.createActionButtons([
                        //{ class: `btn-info ${isBuiltin ? 'disabled' : ''}`, icon: 'fa fa-users', modal: '#users-recipient-modal', title: `${i18n_ext.recipient}` },
                        { class: '' /* Builtins are editable to change theis severity */, icon: 'fa-edit', modal: '#edit-recipient-modal', title: `${i18n_ext.edit}` },
                        { class: `btn-danger ${isBuiltin ? 'disabled' : ''}`, icon: 'fa-trash', modal: '#remove-recipient-modal', title: `${i18n_ext.delete}` },
                    ]);
                }
            },
            {
                data: 'recipient_name'
            },
            {
                data: `endpoint_key`,
                width: '15%',
                render: (endpointType, type, recipient) => {

                    if (type == "display") {

                        let badge = '';
                        const isBuiltin = (recipient.endpoint_conf && recipient.endpoint_conf.builtin) || false;

                        if (isBuiltin) {
                            badge = `<span class='badge bg-dark'>built-in</span>`;
                        }

                        return `${i18n_ext.endpoint_types[endpointType]} ${badge}`;
                    }

                    if (type == 'filter') {
                        return endpointType;
                    }

                    return i18n_ext.endpoint_types[endpointType] || ""
                }
            },
            {
                data: 'endpoint_conf_name',
                render: (endpointName, type, recipient) => {

                    if (type == "display") {

                        const destPage = NtopUtils.buildURL(`${http_prefix}/lua/admin/endpoint_notifications_list.lua`, {
                            endpoint_conf_name: recipient.endpoint_conf_name
                        });

                        return (`<a href='${destPage}'>${endpointName}</a>`);
                    }

                    return endpointName;
                }
            },
            {
                data: "stats.last_use",
                className: "text-center",
                width: "15%",
                render: $.fn.dataTableExt.absoluteFormatSecondsToHHMMSS
            },
            {
                data: "stats.num_uses",
                className: "text-right",
                width: "10%",
                render: function (data, type) {
                    if (type === "display") return NtopUtils.fint(data);
                    return data;
                }
            },
            {
                data: "stats.num_drops",
                className: "text-right",
                width: "10%",
                render: function (data, type) {
                    if (type == "display") return NtopUtils.fint(data);
                    return data;
                }
            },
            {
                data: "stats.fill_pct",
                className: "text-right",
                width: "5%",
                render: function (data, type) {
                    if (type == "display") return NtopUtils.fpercent(data);
                    return data;
                }
            },
            {
                data: "notifications_type",
                className: "text-center text-nowrap",
                width: "5%",
                render: function (data, type, row) {
                    let notification_id = '';
                    {% for id, notification_info in pairs(notifications.notification_types) do %}
                        notification_id = '{{ id }}';
                        if(data && data === notification_id) {
                            return `<i class="{{ notification_info.icon }}" title="{{ notification_info.title }}"></i>`;
                        }
                    {% end %}
                    return '-';
                }  
            },
            {
                data: "check_categories",
                className: "text-right",
                width: "5%",
                render: function (data, type, row) {
                    /* In case no the notification type is not alerts, this data has no meaning */
                    if ((row.notifications_type && row.notifications_type != "alerts")
                        || (row.checks.length > 0))
                        return "-"
                    else if (data.length == 0)
                        return `<i class='text-danger fas fa-exclamation-triangle'></i> ` + data.length;
                    else
                        return data.length;
                }  
            },
            {
                data: "check_entities",
                className: "text-right",
                width: "5%",
                render: function (data, type, row) {
                    if ((row.notifications_type && row.notifications_type != "alerts")
                        || (row.checks.length > 0))
                        return "-"
                    else if (data.length == 0)
                        return `<i class='text-danger fas fa-exclamation-triangle'></i> ` + data.length;
                    else
                        return data.length;
                }  
            },
            {
                data: "checks",
                className: "text-right text-nowrap",
                width: "5%",
                render: function (data, type) {
                    if (data.length == 0) 
                        return '-';
                    else
                        return data.length;
                }  
            },
            {
                data: "minimum_severity",
                className: "text-right text-nowrap",
                width: "5%",
                render: function (data, type, row) {
                    if ((row.notifications_type && row.notifications_type != "alerts") 
                        || (row.checks.length > 0)) {
                        return "-"
                    } else { 
                        const min_sev_key = SEVERITIES[data - 1];
                        return `${i18n_ext.endpoint_severities[min_sev_key]}`;
                    }
                }  
            },
            {
                data: "silence_alerts",
                className: "text-center text-nowrap",
                width: "5%",
                render: function (data, type, row) {
                    /* The buildin recipient cannot be modified and deliver all alerts */
                    if (row.notifications_type && row.notifications_type != "alerts")
                        return "-"
                    else if(data && data === "false" || row.recipient_id == 0) {
                        return `<i class="fas fa-times text-danger"></i>`
                    } else {
                        return `<i class="fas fa-check text-success"></i>`
                    }
                }  
            },
	    /*
            {
                data: "bind_to_pools",
                className: "text-right text-nowrap",
                width: "5%",
                render: function (data, type) {
                    if(data)
                        return data + ` ${i18n_ext.pools}`;
                    else
                        return `<i class='text-danger fas fa-exclamation-triangle'></i> 0 ` + `${i18n_ext.pools}`;
                }  
            },
	    */
        ],
        hasFilters: true,
        stateSave: true,
        initComplete: function (settings, json) {

            const tableAPI = settings.oInstance.api();

            // initialize add button tooltip
            if (!CAN_CREATE_RECIPIENT) {
                // wrap the button inside a span to show tooltip as request by the bootstrap framework
                $(`#btn-add-recipient`).wrap(function() {
                    return `<span id='suggest-tooltip' title='${i18n_ext.createEndpointFirst}' class='d-inline-block' data-toggle='tooltip'></span>`;
                });
                $(`#suggest-tooltip`).tooltip();
            }

            // when the data has been fetched check if the url has a recipient_id param
            // if the recipient is builtin then cancel the modal opening
            DataTableUtils.openEditModalByQuery({
                paramName: 'recipient_id',
                datatableInstance: tableAPI,
                modalHandler: $editRecipientModal,
                cancelIf: (recipient) => recipient.endpoint_conf.builtin,
            });

            // reload data each TABLE_DATA_REFRESH milliseconds
            setInterval(() => { tableAPI.ajax.reload(); }, TABLE_DATA_REFRESH);
        }
    });

    const $recipientsTable = $(`table#recipient-list`).DataTable(dtConfig);
    DataTableUtils.addToggleColumnsDropdown($recipientsTable);

    const endpointTypeFilterMenu = new DataTableFiltersMenu({
        filterTitle: i18n_ext.endpoint_type,
        filters: endpointTypeFilters,
        columnIndex: COLUMN_INDEX_ENDPOINT_TYPE,
        tableAPI: $recipientsTable,
        filterMenuKey: 'endpoint-type'
    }).init();

    /* bind add endpoint event */
    $(`#add-recipient-modal form`).modalHandler({
        method: 'post',
        endpoint: `${http_prefix}/lua/edit_notification_recipient.lua`,
        csrf: pageCsrf,
        resetAfterSubmit: false,
        beforeSumbit: () => {

            $(`#add-recipient-modal form button[type='submit']`).click(function () {
                $(`#add-recipient-modal form span.invalid-feedback`).hide();
            });

            $(`#add-recipient-modal .test-feedback`).hide();

            const data = makeFormData(`#add-recipient-modal form`);
            data.action = 'add';

            return data;
        },
        onModalInit: () => { 
            createTemplateOnSelect(`#add-recipient-modal`);
            // load the template of the selected endpoint
            const $cloned = cloneTemplate($(`#add-recipient-modal select[name='endpoint'] option:selected`).data('endpointKey'));
            if ($cloned) {
                $(`#add-recipient-modal form .recipient-template-container`).empty().append($(`<hr>`), $cloned).show();
            }

            $('#add_recipient_alert_select').select2({
                width: '100%',
                height: '500px',
                theme: 'bootstrap-5',
                dropdownParent: $('#add_recipient_alert_select').parent(),
                dropdownAutoWidth : true,
                maximumSelectionLength: 10,
                placeholder: "{{ i18n('endpoint_notifications.select_alert') }}" 
            });

            $(`#generic_tab`).click(() => {
                $(`#add-recipient-modal form [for='generic_tab']`).addClass('btn-primary');
                $(`#add-recipient-modal form [for='generic_tab']`).removeClass('btn-secondary');
                $(`#add-recipient-modal form [for='per_alerts_tab']`).removeClass('btn-primary');
                $(`#add-recipient-modal form [for='per_alerts_tab']`).addClass('btn-secondary');
                $(`#per_alerts_recipient`).attr('hidden', 'hidden');
                $(`#generic_recipient`).removeAttr('hidden');
            })

            $(`#per_alerts_tab`).click(() => {
                $(`#add-recipient-modal form [for='per_alerts_tab']`).addClass('btn-primary');
                $(`#add-recipient-modal form [for='per_alerts_tab']`).removeClass('btn-secondary');
                $(`#add-recipient-modal form [for='generic_tab']`).removeClass('btn-primary');
                $(`#add-recipient-modal form [for='generic_tab']`).addClass('btn-secondary');
                $(`#generic_recipient`).attr('hidden', 'hidden');
                $(`#per_alerts_recipient`).removeAttr('hidden');
            })
        },
        onModalShow: () => {
            // load the template of the selected endpoint
            const $cloned = cloneTemplate($(`#add-recipient-modal select[name='endpoint'] option:selected`).data('endpointKey'));
            if ($cloned) {
                $(`#add-recipient-modal form .recipient-template-container`).empty().append($(`<hr>`), $cloned).show();
            }   
            
            $(`#add-recipient-modal form [name='show_advanced_prefs']`).on('change', function() {
                const value = $(this).is(':checked')
                $('.advanced-pref').each(function(i, obj) {
                    if(!value) {
                        obj.setAttribute('hidden', 'hidden');
                    } else {
                        obj.removeAttribute('hidden');
                    }
                });
                if(value) {
                    $('#simple-view').removeClass('active');
                    $('#simple-view').removeClass('btn-primary');
                    $('#simple-view').addClass('btn-secondary');
                    $('#expert-view').addClass('active');
                    $('#expert-view').removeClass('btn-secondary');
                    $('#expert-view').addClass('btn-primary');
                } else {
                    $('#expert-view').removeClass('active');
                    $('#expert-view').removeClass('btn-primary');
                    $('#expert-view').addClass('btn-secondary');
                    $('#simple-view').addClass('active');
                    $('#simple-view').removeClass('btn-secondary');
                    $('#simple-view').addClass('btn-primary');
                }
            });

            $(`#add-recipient-notifications-type`).change((item) => {
                if(item && item.target) {
                    if(item.target.value == 'alerts') {
                        $(`#alert_filters`).removeAttr('hidden');
                    } else {
                        $(`#alert_filters`).attr('hidden', 'hidden');
                    }
                }
            });
            $(`#alert_filters`).removeAttr('hidden');
        },
        onSubmitSuccess: function (response) {

            if (response.result.status == "OK") {
                $(`#add-recipient-modal`).modal('hide');
                $(`#add-recipient-modal form .recipient-template-container`).hide();
                $recipientsTable.ajax.reload();
                return;
            }

            if (response.result.error) {
                const localizedString = i18n[response.result.error.type];
                $(`#add-recipient-modal form span.invalid-feedback`).text(localizedString).show();
            }
        }
    }).invokeModalInit();

    const $editRecipientModal = $('#edit-recipient-modal form').modalHandler({
        method: 'post',
        csrf: pageCsrf,
        endpoint: `${http_prefix}/lua/edit_notification_recipient.lua`,
        resetAfterSubmit: false,
        beforeSumbit: function () {
            const data = makeFormData(`#edit-recipient-modal form`);
            data.action = 'edit';
            data.recipient_id = $(`#edit-recipient-modal form [name='recipient_id']`).val();
            return data;
        },
        onModalInit: function (recipient) {
            $(`#edit-recipient-modal .test-feedback`).hide();

            $('#edit_recipient_alert_select').select2({
                width: '100%',
                height: '500px',
                theme: 'bootstrap-5',
                dropdownParent: $('#edit_recipient_alert_select').parent(),
                dropdownAutoWidth : true,
                maximumSelectionLength: 10,
                placeholder: "{{ i18n('endpoint_notifications.select_alert') }}"
            });
            // if there are no recipients params it means there are no inputs except the recipient's name
            if (recipient.recipient_params.length === undefined) {
                /* load the template from templates inside the page */
                const $cloned = cloneTemplate(recipient.endpoint_key);
                $(`#edit-recipient-modal form .recipient-template-container`)
                    .empty().append($(`<hr>`)).append($cloned).show();
            }
            else {
                $(`#edit-recipient-modal form .recipient-template-container`).empty().hide();
            }

	    if (recipient.recipient_id == DEFAULT_RECIPIENT_ID) {
	       $(`#edit-recipient-modal .hide-on-default-recipient`).hide(); 
	    } else {
	       $(`#edit-recipient-modal .hide-on-default-recipient`).show(); 
	    }

            $(`#edit-recipient-name`).text(recipient.recipient_name);
            /* load the values inside the template */
            $(`#edit-recipient-modal form [name='recipient_id']`).val(recipient.recipient_id || DEFAULT_RECIPIENT_ID);
            $(`#edit-recipient-modal form [name='recipient_name']`).val(recipient.recipient_name);
	    if(recipient.endpoint_conf.builtin)
		$(`#edit-recipient-modal form [name='recipient_name']`).attr('readonly', '');
            $(`#edit-recipient-modal form [name='endpoint_conf_name']`).val(recipient.endpoint_conf_name);
            $(`#edit-recipient-modal form [name='recipient_minimum_severity']`).val(recipient.minimum_severity);
            if(recipient.silence_alerts === "false") {
                $(`#edit-recipient-modal form [name='recipient_silence_alerts']`).prop('checked', false); 
            }
            $(`#edit-recipient-modal form [name='recipient_notifications_type']`).val(recipient.notifications_type || "alerts");

            $(`#edit-recipient-modal form [name='recipient_check_categories']`).val(recipient.check_categories);
            $(`#edit-recipient-modal form [name='recipient_check_categories']`).selectpicker('refresh');

            $(`#edit-recipient-modal form [name='recipient_check_entities']`).val(recipient.check_entities);
            $(`#edit-recipient-modal form [name='recipient_check_entities']`).selectpicker('refresh');

            $(`#edit-recipient-modal form [name='recipient_host_pools']`).val(recipient.host_pools);
            $(`#edit-recipient-modal form [name='recipient_host_pools']`).selectpicker('refresh');

            $(`#edit-recipient-modal form [name='recipient_am_hosts']`).val(recipient.am_hosts);
            $(`#edit-recipient-modal form [name='recipient_am_hosts']`).selectpicker('refresh');

            const checks_array = recipient.checks || [];
            $(`#edit_recipient_alert_select`).val(checks_array).trigger('change');

            $(`#edit-recipient-modal form .recipient-template-container [name]`).each(function (i, input) {
                $(this).val(recipient.recipient_params[$(this).attr('name')]);
            });

            if(recipient.notifications_type && recipient.notifications_type == "vulnerability_scans") {
                $(`#edit_alert_filters`).attr('hidden', 'hidden');
            } else {
                $(`#edit_alert_filters`).removeAttr('hidden');
            }

            $(`#edit-recipient-notifications-type`).change((item) => {
                if(item && item.target) {
                    if(item.target.value == 'alerts') {
                        $(`#edit_alert_filters`).removeAttr('hidden');
                    } else {
                        $(`#edit_alert_filters`).attr('hidden', 'hidden');
                    }
                }
            });
            
            if(recipient.checks.length > 0) {
                $(`#edit-recipient-modal form [for='edit_per_alerts_tab']`).addClass('btn-primary');
                $(`#edit-recipient-modal form [for='edit_per_alerts_tab']`).removeClass('btn-secondary');
                $(`#edit-recipient-modal form [for='edit_generic_tab']`).removeClass('btn-primary');
                $(`#edit-recipient-modal form [for='edit_generic_tab']`).addClass('btn-secondary');
                $(`#edit_generic_recipient`).attr('hidden', 'hidden');
                $(`#edit_per_alerts_recipient`).removeAttr('hidden');
            } else {
                $(`#edit-recipient-modal form [for='edit_generic_tab']`).addClass('btn-primary');
                $(`#edit-recipient-modal form [for='edit_generic_tab']`).removeClass('btn-secondary');
                $(`#edit-recipient-modal form [for='edit_per_alerts_tab']`).removeClass('btn-primary');
                $(`#edit-recipient-modal form [for='edit_per_alerts_tab']`).addClass('btn-secondary');
                $(`#edit_per_alerts_recipient`).attr('hidden', 'hidden');
                $(`#edit_generic_recipient`).removeAttr('hidden');
            }

            /* bind testing button */
            $(`#edit-test-recipient`).off('click').click(async function (e) {
                e.preventDefault();
                const $self = $(this);
                $self.attr("disabled");
                const data = makeFormData(`#edit-recipient-modal form`);
                data.endpoint_id = recipient.endpoint_id;
                testRecipient(data, $(this), $(`#edit-recipient-modal .test-feedback`)).then(() => {
                    $self.removeAttr("disabled");
                });
            });
            $(`#edit_per_alerts_tab`).click(() => {
                $(`#edit-recipient-modal form [for='edit_per_alerts_tab']`).addClass('btn-primary');
                $(`#edit-recipient-modal form [for='edit_per_alerts_tab']`).removeClass('btn-secondary');
                $(`#edit-recipient-modal form [for='edit_generic_tab']`).removeClass('btn-primary');
                $(`#edit-recipient-modal form [for='edit_generic_tab']`).addClass('btn-secondary');
                $(`#edit_generic_recipient`).attr('hidden', 'hidden');
                $(`#edit_per_alerts_recipient`).removeAttr('hidden');
            })
            $(`#edit_generic_tab`).click(() => {
                $(`#edit-recipient-modal form [for='edit_generic_tab']`).addClass('btn-primary');
                $(`#edit-recipient-modal form [for='edit_generic_tab']`).removeClass('btn-secondary');
                $(`#edit-recipient-modal form [for='edit_per_alerts_tab']`).removeClass('btn-primary');
                $(`#edit-recipient-modal form [for='edit_per_alerts_tab']`).addClass('btn-secondary');
                $(`#edit_per_alerts_recipient`).attr('hidden', 'hidden');
                $(`#edit_generic_recipient`).removeAttr('hidden');
            })
        },
        onModalShow: function () {
            $(`#edit-recipient-modal .test-feedback`).hide();
        },
        onSubmitSuccess: function (response) {
            if (response.result.status == "OK") {
                $(`#edit-recipient-modal`).modal('hide');
                $recipientsTable.ajax.reload();
            }

            if (response.result.error) {
                const localizedString = getInvalidMessage(`#edit-recipient-modal form`, response.result.error.missing_param);
                $(`#edit-recipient-modal form .invalid-feedback`).text(localizedString).show();
            }
        }
    });

    const $removeRecipientModal = $(`#remove-recipient-modal form`).modalHandler({
        method: 'post',
        csrf: pageCsrf,
        endpoint: `${http_prefix}/lua/edit_notification_recipient.lua`,
        dontDisableSubmit: true,
        onModalInit: (recipient) => {
            $(`.removed-recipient-name`).text(`${recipient.recipient_name}`);
        },
        beforeSumbit: (recipient) => {
            return {
                action: 'remove',
                recipient_id: recipient.recipient_id || DEFAULT_RECIPIENT_ID
            }
        },
        onSubmitSuccess: (response) => {
            if (response.result) {
                $(`#remove-recipient-modal`).modal('hide');
                $recipientsTable.ajax.reload();
            }
        }
    });

    /* bind edit recipient event */
    $(`table#recipient-list`).on('click', `a[href='#edit-recipient-modal']`, function (e) {

        const selectedRecipient = $recipientsTable.row($(this).parent().parent().parent().parent()).data();

        $editRecipientModal.invokeModalInit(selectedRecipient);
    });

    /* bind remove endpoint event */
    $(`table#recipient-list`).on('click', `a[href='#remove-recipient-modal']`, function (e) {

        const selectedRecipient = $recipientsTable.row($(this).parent().parent().parent().parent()).data();
        // prevent removing builtin
        if (selectedRecipient.endpoint_conf.builtin) {
            e.preventDefault();
            return;
        }

        $removeRecipientModal.invokeModalInit(selectedRecipient);
    });

    /* bind recipient users button */
    /*
    $(`table#recipient-list`).on('click', `a[href='#users-recipient-modal']`, async function () {

        const { recipient_id, recipient_name } = $recipientsTable.row($(this).parent().parent().parent().parent()).data();
        $(`.recipient-name`).text(recipient_name);
        $(`.fetch-failed,.zero-user`).hide();

        try {

            const response = await fetch(`${http_prefix}/lua/rest/v2/get/recipient/pools.lua?recipient_id=${recipient_id}`);
            const { rsp } = await response.json();

            // if there are no pools for the selected recipient shows a message
            if (rsp.length == 0) {
                $(`.zero-user`).show();
                $(`#users-recipient-modal .list-group`).hide();
                return;
            }

            generateUsersList(rsp);

        }
        catch (err) {
            console.warn('Unable to show the recipient users');
            $(`.fetch-failed`).show();
        }
    });
    */

    $(`#add-test-recipient`).click(async function (e) {

        e.preventDefault();

        const $self = $(this);

        testRecipient(makeFormData(`#add-recipient-modal form`), $(this), $(`#add-recipient-modal .test-feedback`))
            .then(() => { $self.removeAttr("disabled"); });
    });

    $(`[name='recipient_check_categories']`).on('changed.bs.select', function (e, clickedIndex, isSelected, previousValue) {

        const lessThanOne = $(this).val().length < 1;

        if (lessThanOne) {
            $(this).val(previousValue);
            $(this).selectpicker('refresh');
        }
    });

    $(`[name='recipient_check_entities']`).on('changed.bs.select', function (e, clickedIndex, isSelected, previousValue) {

        const lessThanOne = $(this).val().length < 1;

        if (lessThanOne) {
            $(this).val(previousValue);
            $(this).selectpicker('refresh');
        }
    });

    $(`[name='recipient_host_pools']`).on('changed.bs.select', function (e, clickedIndex, isSelected, previousValue) {
        if (!$(this).hasClass("allow-no-selection")) {
            const lessThanOne = $(this).val().length < 1;

            if (lessThanOne) {
                $(this).val(previousValue);
                $(this).selectpicker('refresh');
            }
        }
    });

    $(`[name='recipient_am_hosts']`).on('changed.bs.select', function (e, clickedIndex, isSelected, previousValue) {
        if (!$(this).hasClass("allow-no-selection")) {
            const lessThanOne = $(this).val().length < 1;

            if (lessThanOne) {
                $(this).val(previousValue);
                $(this).selectpicker('refresh');
            }
        }
    });

</script>
