<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 { AgGridVue } from "ag-grid-vue3" // Vue Grid Logic
import { 
  ModuleRegistry, 
  AllCommunityModule, 
  provideGlobalGridOptions,
  CustomFilterModule, 
} from "ag-grid-community"
import { 
  LicenseManager, 
  RowGroupingModule, 
  MasterDetailModule, 
  ContextMenuModule, 
  ExcelExportModule 
} from 'ag-grid-enterprise';

ModuleRegistry.registerModules([
  AllCommunityModule,
  RowGroupingModule, 
  MasterDetailModule, 
  ContextMenuModule,
  ExcelExportModule,
  CustomFilterModule, 
])
provideGlobalGridOptions({ theme: "legacy" })

const config = useRuntimeConfig()

LicenseManager.setLicenseKey(config.public.aggrid)

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],
  rowClassRules: Object,
})

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

const gridApi = ref();
const defaultColDef = ref({
  filter: false,
  editable: false,
  sortable: false,
  suppressHeaderMenuButton: true,
  suppressHeaderFilterButton: false,
  suppressHeaderContextMenu: true,
})

const gridOptions = ref({
  maintainColumnOrder: true,
  suppressScrollOnNewData: true,
})
const columnTypes = ref({
  nonEditableColumn: { editable: false },
  editableColumn: { editable: true }
})

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
    :gridOptions="gridOptions"
    :autoSizeStrategy="autoSizeStrategy"
    :rowData="entries"
    :columnDefs="columns"
    :defaultColDef="defaultColDef"
    :columnTypes="columnTypes"
    :pagination="false"
    :suppressPaginationPanel="true"
    :paginationPageSize="100"
    rowSelection="multiple"
    :columnMenu="columnMenu ?? null"
    :rowClassRules="rowClassRules ?? null"
    :masterDetail="masterDetail ?? false"
    :detailCellRenderer="masterDetailRenderer ?? null"
    :detailCellRendererParams="masterDetailParams ?? null"
    :suppressScrollOnNewData="true"
    @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>