<script setup>
import "ag-grid-community/styles/ag-grid.css" // Core CSS
//import "ag-grid-community/styles/ag-theme-quartz.css" // Theme
//import "ag-grid-community/styles/ag-theme-material.css" // Theme
import "ag-grid-community/styles/ag-theme-balham.css" // Theme

import { ModuleRegistry, AllCommunityModule, provideGlobalGridOptions } from "ag-grid-community"
import { AgGridVue } from "ag-grid-vue3" // Vue Grid Logic
import {
  LicenseManager,
  RowGroupingModule,
  MasterDetailModule,
  ContextMenuModule,
  ExcelExportModule,
  SetFilterModule,
  FiltersToolPanelModule,
  ColumnsToolPanelModule,
  SideBarModule,
  PivotModule
} from 'ag-grid-enterprise';

ModuleRegistry.registerModules([
  AllCommunityModule,
  RowGroupingModule,
  MasterDetailModule,
  ContextMenuModule,
  ExcelExportModule,
  SetFilterModule,
  FiltersToolPanelModule,
  ColumnsToolPanelModule,
  SideBarModule,
  PivotModule
])
provideGlobalGridOptions({ theme: "legacy" })

const config = useRuntimeConfig()

LicenseManager.setLicenseKey(config.public.aggrid)

const props = defineProps({
  entries: Array, // Row Data: The data to be displayed.
  columns: Array, // Column Definitions: Defines & controls grid columns.
  masterDetail: Boolean,
  masterDetailRenderer: Object,
  masterDetailParams: Object,
  columnMenu: [String, Object],
  enableFilter: { type: Boolean, default: false },
  enableGrouping: { type: Boolean, default: false },
  sideBar: { type: [Boolean, String, Object], default: false },
  groupAggFiltering: { type: Boolean, default: false },
  grandTotalRow: { type: String, default: null }, // 'top' or 'bottom'
  // When true, AG Grid shows its built-in loading spinner overlay instead of the
  // "No Rows" overlay. Lets list pages fetch lazily (lazy: true) so navigation is
  // not blocked, while still giving the operator a spinner until rows arrive.
  loading: { type: Boolean, default: false }
})

const emit = defineEmits(['cellClick', 'cellChange'])

// Org-bpartner isDisallowExport flag: suppresses AG Grid's built-in
// context-menu CSV/Excel export on client-side grids.
const { allowExport, load: loadExportFlag } = useDisallowExport()
onMounted(() => { loadExportFlag() })

const gridApi = ref();
const defaultColDef = computed(() => ({
  filter: props.enableFilter,
  floatingFilter: props.enableFilter,
  editable: false,
  enableRowGroup: props.enableGrouping,
  enablePivot: props.enableGrouping,
  enableValue: props.enableGrouping
}))
const columnTypes = ref({
  nonEditableColumn: { editable: false }
})

const sideBarConfig = computed(() => {
  if (props.sideBar === true) {
    return {
      toolPanels: [
        {
          id: 'columns',
          labelDefault: 'Columns',
          labelKey: 'columns',
          iconKey: 'columns',
          toolPanel: 'agColumnsToolPanel',
        },
        {
          id: 'filters',
          labelDefault: 'Filters',
          labelKey: 'filters',
          iconKey: 'filter',
          toolPanel: 'agFiltersToolPanel',
        }
      ],
      defaultToolPanel: ''
    }
  }
  return props.sideBar
})

const autoSizeStrategy = {
  type: 'fitCellContents',
  // type: 'fitGridWidth',

};

const onGridReady = (params) => {
  gridApi.value = params.api
}

const onCellValueChanged = (event) => {
  emit('cellChange', event)
}

const onSelectionChanged = (event) => {
  emit('cellClick', event, gridApi.value)
}

</script>

<template>
  <!-- The AG Grid component -->
  <AgGridVue
    :autoSizeStrategy="autoSizeStrategy"
    :loading="loading"
    :rowData="entries"
    :columnDefs="columns"
    :defaultColDef="defaultColDef"
    :columnTypes="columnTypes"
    :pagination="true"
    :paginationPageSize="100"
    rowSelection="multiple"
    :columnMenu="columnMenu ?? null"
    :masterDetail="masterDetail ?? false"
    :detailCellRenderer="masterDetailRenderer ?? null"
    :detailCellRendererParams="masterDetailParams ?? null"
    :sideBar="sideBarConfig"
    :rowGroupPanelShow="enableGrouping ? 'always' : 'never'"
    :groupDisplayType="'groupRows'"
    :suppressAggFuncInHeader="true"
    :groupAggFiltering="groupAggFiltering"
    :grandTotalRow="grandTotalRow"
    :alwaysAggregateAtRootLevel="true"
    :suppressCsvExport="!allowExport"
    :suppressExcelExport="!allowExport"
    @grid-ready="onGridReady"
    @cell-value-changed="onCellValueChanged"
    @selection-changed="onSelectionChanged"
    class="ag-theme-balham w-100pct h-600px" />
</template>

<style>
@ref w-100pct h-600px;

.tf-icon.ti {
  font-size: 22px !important;
  margin-top: -1px;
}

</style>