import { defineStore } from 'pinia'

interface FilterValues {
  [x: string]: string[]
}

export const useTableSettingsStore = defineStore('tableSettings', () => {
  const route = useRoute()

  const savedHiddenColumnKeysMap = ref<{ [fullTableName: string]: string[] }>(
    JSON.parse(localStorage.getItem('savedHiddenColumnKeysMap') ?? '{}')
  )
  const saveHiddenColumnKeys = (columnKeys: string[] = [], tableName?: string) => {
    const fullTableName = route.path + (tableName ? `/${tableName}` : '')
    savedHiddenColumnKeysMap.value[fullTableName] = columnKeys
    localStorage.setItem(
      'savedHiddenColumnKeysMap',
      JSON.stringify(savedHiddenColumnKeysMap.value)
    )
  }

  const savedTableFilterValueMap = ref<{
    [fullTableName: string]: FilterValues
  }>(JSON.parse(localStorage.getItem('savedTableFilterValueMap') ?? '{}'))
  const saveTableFilterValues = (
    filterValues: FilterValues,
    tableName?: string
  ) => {
    const fullTableName = route.path + (tableName ? `/${tableName}` : '')
    savedTableFilterValueMap.value[fullTableName] = filterValues
    localStorage.setItem(
      'savedTableFilterValueMap',
      JSON.stringify(savedTableFilterValueMap.value)
    )
  }

  return {
    savedHiddenColumnKeysMap,
    saveHiddenColumnKeys,
    savedTableFilterValueMap,
    saveTableFilterValues,
  }
})
