<script>
import { debounce } from 'lodash';
import { stateFilter, severityFilter, scannerFilter, getProjectFilter } from '../helpers';
import StandardFilter from './filters/standard_filter.vue';

const searchBoxOptionCount = 20; // Number of options before the search box is shown.

export default {
  components: {
    StandardFilter,
  },
  props: {
    projects: { type: Array, required: false, default: undefined },
  },
  data: () => ({
    filterQuery: {},
  }),
  computed: {
    filters() {
      return this.projects
        ? [stateFilter, severityFilter, scannerFilter, getProjectFilter(this.projects)]
        : [stateFilter, severityFilter, scannerFilter];
    },
  },
  methods: {
    updateFilterQuery(query) {
      this.filterQuery = { ...this.filterQuery, ...query };
      this.emitFilterChange();
    },
    // All the filters will emit @filter-changed when the page is first loaded, which will trigger
    // this method multiple times. We'll debounce it so that it only runs once.
    emitFilterChange: debounce(function emit() {
      this.$emit('filterChange', this.filterQuery);
    }),
  },
  searchBoxOptionCount,
};
</script>

<template>
  <div class="dashboard-filters border-bottom bg-gray-light">
    <div class="row mx-0 p-2">
      <standard-filter
        v-for="filter in filters"
        :key="filter.id"
        class="col-sm-6 col-md-4 col-lg-2 p-2"
        :filter="filter"
        :data-testid="filter.id"
        :show-search-box="filter.options.length >= $options.searchBoxOptionCount"
        @filter-changed="updateFilterQuery"
      />
    </div>
  </div>
</template>
