<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,
  DateFilterModule,
  NumberFilterModule,
  TextFilterModule 
} from "ag-grid-community"
import { 
  AllEnterpriseModule, 
  LicenseManager,
  ColumnMenuModule,
  ColumnsToolPanelModule,
  ContextMenuModule,
  FiltersToolPanelModule,
  SetFilterModule 
} from 'ag-grid-enterprise'

const config = useRuntimeConfig()

ModuleRegistry.registerModules([AllEnterpriseModule]);

LicenseManager.setLicenseKey(config.public.aggrid ?? "Using_this_{AG_Grid}_Enterprise_key_{AG-086756}_in_excess_of_the_licence_granted_is_not_permitted___Please_report_misuse_to_legal@ag-grid.com___For_help_with_changing_this_key_please_contact_info@ag-grid.com___{LogYou_GmbH}_is_granted_a_{Single_Application}_Developer_License_for_the_application_{logyou}_only_for_{1}_Front-End_JavaScript_developer___All_Front-End_JavaScript_developers_working_on_{logyou}_need_to_be_licensed___{logyou}_has_not_been_granted_a_Deployment_License_Add-on___This_key_works_with_{AG_Grid}_Enterprise_versions_released_before_{22_April_2026}____[v3]_[01]_MTc3NjgxMjQwMDAwMA==8e4702249545b99c7fe255c8ad2aff09");

const props = defineProps({
  columns: Array, // Column Definitions: Defines & controls grid columns.
  masterDetail: Boolean,
  masterDetailRenderer: Object,
  masterDetailParams: Object,
  columnMenu: [String, Object],
  sourceEndpoint: String,
  rowClassRules: Object,
  filterBySwitch: Object
})

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

const gridApi = ref();
const defaultColDef = ref({
  filter: false,
  editable: true
})
const columnTypes = ref({
  nonEditableColumn: { editable: false },
  editableColumn: { editable: true }
})

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

};

const rowData = ref(null)

const serverSideDatasource = (filter = {}) => {
  return {
    getRows(params) {
      //console.log(JSON.stringify({...params.request, ...filter}, null, 1));

      fetch('/api/'+props.sourceEndpoint, {
        method: 'post',
        body: JSON.stringify({...params.request, ...filter}),
        headers: {"Content-Type": "application/json; charset=utf-8"}
      })
      .then(httpResponse => httpResponse.json())
      .then(response => {
          // console.log(response?.records || [])
          //console.log(response?.rows || [])
          params.success({ rowData: response.rows, rowCount: response.lastRow })
      })
      .catch(error => {
          console.log(error)
          params.fail()
      })
    }
  }
}

const filterBySwitcher = ref(props.filterBySwitch || {})
const onGridReady = (params) => {
  gridApi.value = params.api

  gridApi.value.setGridOption('serverSideDatasource', serverSideDatasource(filterBySwitcher.value))
}

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

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

watch(() => props.filterBySwitch, (filter) => {
  filterBySwitcher.value = filter || props.filterBySwitch || {}
  if(gridApi.value) {
    gridApi.value.refreshServerSide({ route: undefined, purge: true })
  }
}, { deep: true })
</script>

<template>
  <!-- The AG Grid component -->
  <AgGridVue
    :rowData="rowData"
    :autoSizeStrategy="autoSizeStrategy"
    rowModelType="serverSide"
    :columnDefs="columns"
    :defaultColDef="defaultColDef"
    :columnTypes="columnTypes"
    :pagination="true"
    :paginationPageSize="100"
    rowSelection="multiple"
    :columnMenu="columnMenu ?? null"
    :rowClassRules="rowClassRules ?? null"
    :masterDetail="masterDetail ?? false"
    :detailCellRenderer="masterDetailRenderer ?? null"
    :detailCellRendererParams="masterDetailParams ?? null"
    @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>