<script setup>
const dataTableFilters = useDataTableFilters()

const props = defineProps({
  params: Object
})

const filterText = ref('')
const updateFilter = () => {
  let filterValue = {
    ...(dataTableFilters.value?.['salesOrder'] ?? {}),
    name: filterText.value
  }
  if(dataTableFilters.value?.['salesOrder']) {
    dataTableFilters.value['salesOrder'] = filterValue
  } else {
    dataTableFilters.value = {
      salesOrder: filterValue
    }
  }
  props.params?.filterChangedCallback?.()
}

const doesFilterPass = (params) => {
  const { api, colDef, column, context } = props.params;
  const { node } = params;

  // make sure each word passes separately, ie search for firstname, lastname
  let passed = true;
  filterText.value
      .toLowerCase()
      .split(' ')
      .forEach((filterWord) => {
          const value = props.params.getValue(node);

          if (value.toString().toLowerCase().indexOf(filterWord) < 0) {
              passed = false;
          }
      });

  return passed;
}

const isFilterActive = () => {
  return filterText.value != null && filterText.value !== '';
}

const getModel = () => {
  if (!isFilterActive()) {
    return null;
  }

  return { value: filterText.value };
}
const setModel = (model) => {
  filterText.value = model == null ? '' : model.value;
}

const getModelAsString = () => {
  return filterText.value || '';
}

const onFloatingFilterChanged = (type, value) => {
  filterText.value = value || '';
  updateFilter();
}

defineExpose({
  doesFilterPass,
  isFilterActive,
  getModel,
  setModel,
  getModelAsString,
  onFloatingFilterChanged
})
</script>

<template>
  <div class="p-0.75rem">
    <label class="label d-block mb-2">Name</label>
    <input type="text" class="input" v-model="filterText" v-on:keyup.enter="updateFilter($event)" placeholder="Name..."/>
  </div>
</template>