<!--
  (C) 2022 - ntop.org

  Edit categories page
-->

<table id='table-custom-cat-form' class='table table-striped table-bordered w-100'>
  <thead>
    <tr>
      <th>{{ i18n("category") }}</th>
      <th>{{ i18n("users.num_protocols") }}</th>
      <th>{{ i18n("custom_categories.custom_hosts") }}</th>
      <th>{{ i18n("actions") }}</th>
    </tr>
  </thead>
</table>

{# add modals if defined #}
{% if modals then %}
<div class="modals">
    {% for _, modal in pairs(modals) do %}
        {* modal *}
    {% end %}
</div>
{% end %}

<script type="text/javascript">
  const url = '{* http_prefix *}/lua/rest/v2/get/category/list.lua'
  const standardSortingColumn = 0 /* Category name column */
  const urlParams = {
    ifid: {* ifid *},
    l7proto: {* category_filter *}
  }

  $(document).ready(async function() {
    let config = DataTableUtils.getStdDatatableConfig( [ {
      text: '<i class="fas fa-sync"></i>',
      action: function(e, dt, node, config) {
          window.location.reload();
      }
    }]);

    let columns = [
      { name: 'category', data: 'column_category_name', orderable: true, className: 'text-nowrap'},
      { name: 'num_protos', data: 'column_num_protos', className: 'text-nowrap text-center' },
      { name: 'num_hosts', data: 'column_num_hosts', className: 'text-nowrap text-center' },
      { name: 'actions', data: 'column_actions', className: 'text-center',
        render: function() {
          return DataTableUtils.createActionButtons([
            { class: 'btn-info', icon: 'fa-edit', modal: '#edit-category-rules', title: i18n('edit') },
          ]);
        } 
      },
      { name: 'category_id', data: 'column_category_id', visible: false },
      { name: 'category_hosts', data: 'column_category_hosts', visible: false },
    ];

    config = DataTableUtils.extendConfig(config, {
      serverSide: false,
      searching: true,
      order: [[ standardSortingColumn, 'asc' ]],
      ajax: {
        method: 'get',
        url: NtopUtils.buildURL(url, urlParams),
        dataSrc: 'rsp',
        beforeSend: function() {
          NtopUtils.showOverlays();
        },
        complete: function() {
          NtopUtils.hideOverlays();
        }
      },
      columns: columns,
    });
    
    const $table = $('#table-custom-cat-form').DataTable(config);

    const $editCategory = $('#edit-category-rules form').modalHandler({
      method: 'post',
      csrf: '{* csrf *}',
      endpoint: '{* http_prefix *}/lua/rest/v2/edit/category/category.lua',
      beforeSumbit: function (category) {
        let params = {}
        let unique_hosts = []
        /* Cycling the host list in the text area of the modal */
        $.each($("#category-hosts-list").val().split("\n"), function(i, host) {
          let whitelisted = (host.charAt(0) === '!');
          host = NtopUtils.cleanCustomHostUrl(host);
          if (whitelisted) host = "!" + host;

          if($.inArray(host, unique_hosts) === -1)
            unique_hosts.push(host);
        });

        params.category = "cat_" + category.column_category_id;
        params.category_alias = $("#category-name").val();
        params.custom_hosts = unique_hosts.join(',');
        
        return params
      },
      onModalInit: function (category) {
        const categoryList = $('#category-hosts-list')
        let categoryHostList = ''
        categoryList.val('')

        if(category.column_category_hosts !== '') {
          $.each(category.column_category_hosts.split(','), function(i, host) {
            categoryHostList = categoryHostList + host + '\n'
          })

          categoryList.val(categoryHostList)
        }

        $('#category-name').val(category.column_category_name)
      },
      onSubmitSuccess: function (response, dataSent) {
        if(response.rc < 0)
          $('#edit-category-rules_dialog .invalid-feedback').html(i18n('rest.' + response.rc_str || response.rc_str)).show();
        else 
          location.reload()

        return (response.rc == 0);
      }
    });

    $table.on('click', `a[href='#edit-category-rules']`, function (e) {
      const category = $table.row($(this).parent().parent().parent().parent()).data();
      $editCategory.invokeModalInit(category)
    });
  })
</script>
