import React from "react";
import { useTranslation } from "react-i18next";
import { Namespaces } from "../../../../i18n/i18n";
import Column from "../../../../components/common/columns";
import Table, {
  PublishedTableProps,
} from "../../../../components/common/Table";
import authentication from "../../../frame/services/authenticationService";
import { CustomField } from "../services/customFieldsService";

const CustomFieldsTable: React.FC<PublishedTableProps<CustomField>> = (
  props,
) => {
  const { t } = useTranslation(Namespaces.Common);

  const columns: Column<CustomField>[] = [
    { key: "name", label: t("Name"), order: "asc" },
    {
      key: "fieldType",
      label: t("FieldType"),
      order: "asc",
      searchable: false,
    },
  ];

  const raiseSort = (sortColumn: Column<CustomField>) => {
    if (props.onSort !== undefined) props.onSort(sortColumn);
  };

  const handleAuditParams = (item: any) => {
    return {
      entityName: "e_suite.Database.Core.Tables.CustomFields.CustomField",
      primaryKey: '{"Id":' + item.id + "}",
    };
  };

  const { data, sortColumn, onChangePage, onSearch, onDelete } = props;
  const editPath = authentication.hasAccess("EditField")
    ? "edit/{0}"
    : undefined;
  const doDelete = authentication.hasAccess("DeleteField")
    ? onDelete
    : undefined;
  const showAudit = authentication.hasAccess("ViewAuditLog")
    ? handleAuditParams
    : undefined;

  return (
    <Table
      data={data}
      keyName="id"
      columns={columns}
      sortColumn={sortColumn}
      editPath={editPath}
      onSort={raiseSort}
      onChangePage={onChangePage}
      onSearch={onSearch}
      onDelete={doDelete}
      onAuditParams={showAudit}
    />
  );
};

export default CustomFieldsTable;
