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

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

export default {
  props: {
    projects: { type: Array, required: false, default: undefined },
  },
  data: () => ({
    filterQuery: {},
  }),
  computed: {
    filters() {
      const filters = [stateFilter, severityFilter, scannerFilter, activityFilter];

      if (this.projects) {
        filters.push(getProjectFilter(this.projects));
      }

      return filters;
    },
  },
  methods: {
    updateFilterQuery(query) {
      this.filterQuery = { ...this.filterQuery, ...query };
      this.emitFilterChange();
    },
    // When this component is first shown, every filter will emit its own @filter-changed event at,
    // 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);
    }),
    getFilterComponent({ id }) {
      if (id === activityFilter.id) {
        return ActivityFilter;
      } else if (gon.features?.customSecurityScanners && id === scannerFilter.id) {
        return ScannerFilter;
      }

      return StandardFilter;
    },
  },
  searchBoxOptionCount,
};
</script>

<template>
  <div class="dashboard-filters border-bottom bg-gray-light">
    <div class="row mx-0 p-2">
      <component
        :is="getFilterComponent(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>
