<!--
  (C) 2013-23 - ntop.org
-->

<template>
  <div class="row">
    <div class="col-md-12 col-lg-12">
      <div class="card card-shadow">
        <div class="card-body">
          
          
          <div id="vs_reports">
            <ModalDeleteReportConfirm
              ref="modal_delete_confirm"
              :title="title_delete"
              :body="body_delete"
              @delete="delete_row"
            >
            </ModalDeleteReportConfirm>
            <TableWithConfig
              ref="table_vs_reports"
              :table_id="table_id"
              :csrf="context.csrf"
              :f_map_columns="map_table_def_columns"
              :get_extra_params_obj="get_extra_params_obj"
              :f_sort_rows="columns_sorting"
              @custom_event="on_table_custom_event"
              @rows_loaded="on_table_loaded"
            >
            </TableWithConfig>
          </div>
        </div>
    
        
      </div>
    </div>
  </div>
  <ModalEditReport
    ref="modal_edit"
    :context="context"
    @edit="edit"
  >
  </ModalEditReport>
</template>
  
<script setup>
/* Imports */
import { ref, onBeforeMount, onMounted } from "vue";
import { default as NoteList } from "./note-list.vue";
import { default as TableWithConfig } from "./table-with-config.vue";
import { ntopng_url_manager } from "../services/context/ntopng_globals_services.js";
import { ntopng_utility } from "../services/context/ntopng_globals_services";
import { default as ModalEditReport } from "./modal-edit-vs-report.vue";
import { default as ModalDeleteReportConfirm } from "./modal-delete-scan-confirm.vue";
import { default as sortingFunctions } from "../utilities/sorting-utils.js";


/* ******************************************************************** */

/* Consts */
const _i18n = (t) => i18n(t);

const note = i18n(
  "hosts_stats.page_scan_hosts.notes.generic_notes_1"
).replaceAll("${http_prefix}", `${http_prefix}`);
const note_list = [note];

const title_delete = _i18n("hosts_stats.page_scan_hosts.report_page.delete_title");
const body_delete = _i18n("hosts_stats.page_scan_hosts.report_page.delete_description");


const open_report_url = `${http_prefix}/lua/enterprise/vulnerability_scan_report.lua`;
const remove_report_url = `${http_prefix}/lua/pro/rest/v2/delete/vs/report.lua`;
const edit_report_url = `${http_prefix}/lua/pro/rest/v2/edit/vs/report.lua`;

const table_id = ref("vs_reports");
const table_vs_reports = ref();
const modal_edit = ref();
const modal_delete_confirm = ref();
const total_rows = ref(0);
const row_to_delete = ref({});

const props = defineProps({
  context: Object,
});
const rest_params = {
  csrf: props.context.csrf,
};
const context = ref({
  csrf: props.context.csrf,
  ifid: props.context.ifid,
});

let scan_type_list = [];
let get_scan_type_list_v = null;

/* ******************************************************************** */

/* Function to refresh table */
function refresh_table() {
  table_vs_reports.value.refresh_table();
}

/* ******************************************************************** */

const get_extra_params_obj = () => {
  let extra_params = ntopng_url_manager.get_url_object();
  return extra_params;
};

/* ******************************************************************** */

/* Function to handle all buttons */
function on_table_custom_event(event) {
  let events_managed = {
    click_button_edit: click_button_edit,
    click_button_delete: click_button_delete,
  };
  if (events_managed[event.event_id] == null) {
    return;
  }
  events_managed[event.event_id](event);
}

/* ******************************************************************** */

/* This function simply return the data of the exact column and row requested */
function column_data(col, row) {
  let data = row[col.data.data_field];

  if (col.data.data_field == 'report_date') {
    data = row['epoch']
  }

  if (col.data.data_field == 'name') {
    data = format_report_name(row['name'], row['epoch'])
  }

  return data;
}

/* ******************************************************************** */

/* Default sorting, by date in DESC order */
function compare_by_report_date(r0, r1) {
  return sortingFunctions.sortByNumber(
    r0["epoch"],
    r1["epoch"],
    0 /* by default asc */
  );
}

/* Specific function for report name because could be "Report of date" (default) or a custom name */
function format_report_name(report_name, epoch) {
  
  let formatted_report_name = report_name;
  
  if (report_name.startsWith("Report of")) {
    formatted_report_name = 'report_'+epoch;   
  }

  return formatted_report_name;

}

/* ******************************************************************** */

/* Function used to sort the columns of the table */
function columns_sorting(col, r0, r1) {
  if (col != null) {
    let r0_col = column_data(col, r0);
    let r1_col = column_data(col, r1);

    /* In case the values are the same, sort by IP */
    if (r0_col == r1_col) {
      return compare_by_report_date(r0, r1);
    }
    
    if (col.id == "report_date") {
      return sortingFunctions.sortByNumber(r0_col, r1_col, col.sort);
    } else if (col.id == "tcp_ports" || col.id == "udp_ports") {
      return sortingFunctions.sortByNumber(r0_col, r1_col, col.sort);
    } else if (col.id == "cves") {
      return sortingFunctions.sortByNumber(r0_col, r1_col, col.sort);
    } else if (col.id == "name") {
      return sortingFunctions.sortByName(r0_col, r1_col, col.sort);
    } else if (col.id == "num_hosts") {
      return sortingFunctions.sortByNumber(r0_col, r1_col, col.sort);
    } else {
      return sortingFunctions.sortByName(r0_col, r1_col, col.sort);
    }
  }

  return compare_by_report_date(r0, r1);
}


/* ******************************************************************** */

/* Function to handle delete button */
function click_button_delete(event) {
  row_to_delete.value = event.row;
  modal_delete_confirm.value.show("delete_single_report");
}



/* ******************************************************************** */

/* Function to handle edit button */
function click_button_edit(event) {
  modal_edit.value.show(event.row);
}

/* ******************************************************************** */

/* Function to edit report */
async function edit(params) {
  await edit_report_rest(params);
}

const edit_report_rest = async function (params) {
  const url = NtopUtils.buildURL(edit_report_url, {
    ...params,
  });

  const result = await ntopng_utility.http_post_request(url, rest_params);

  refresh_table();
};

/* ******************************************************************** */

/* Get the number of rows of the table */
function on_table_loaded() {
  total_rows.value = table_vs_reports.value.get_rows_num();
}

/* ******************************************************************** */

/* Function to map columns data */
const map_table_def_columns = (columns) => {


  let map_columns = {
    "report_date": (report_date, row) => {
        const url = NtopUtils.buildURL(open_report_url, {
        printable: false,
        epoch_end: row.epoch,
        epoch_begin: row.epoch
      });
    
    return `<a href="${url}">${report_date}</a>`;
    },
  };

  columns.forEach((c) => {
    c.render_func = map_columns[c.data_field];

    
  });
  
  return columns;
};

/* ************************** REST Functions ************************** */


/* ******************************************************************** */

/* Function to delete report */
const delete_row = async function () {
  const row = row_to_delete.value;
  const url = NtopUtils.buildURL(remove_report_url, {
    epoch: row.epoch
  });
  debugger;
  await ntopng_utility.http_post_request(url, rest_params);
  refresh_table(false);
};

/* ******************************************************************** */
</script>
  