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

export default {
  components: { StandardFilter, ScannerFilter, ActivityFilter },
  inject: ['dashboardType'],
  props: {
    projects: { type: Array, required: false, default: undefined },
  },
  data() {
    return {
      filterQuery: {},
      standardFilters: [stateFilter, severityFilter],
    };
  },
  computed: {
    isPipeline() {
      return this.dashboardType === DASHBOARD_TYPES.PIPELINE;
    },
    shouldShowProjectFilter() {
      return Boolean(this.projects?.length);
    },
    projectFilter() {
      return getProjectFilter(this.projects);
    },
  },
  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);
    }),
  },
  scannerFilter,
  activityFilter,
};
</script>

<template>
  <div
    class="vulnerability-report-filters gl-p-5 gl-bg-gray-10 gl-border-b-1 gl-border-b-solid gl-border-b-gray-100"
  >
    <standard-filter
      v-for="filter in standardFilters"
      :key="filter.id"
      :filter="filter"
      :data-testid="filter.id"
      @filter-changed="updateFilterQuery"
    />
    <scanner-filter :filter="$options.scannerFilter" @filter-changed="updateFilterQuery" />
    <activity-filter
      v-if="!isPipeline"
      :filter="$options.activityFilter"
      @filter-changed="updateFilterQuery"
    />
    <standard-filter
      v-if="shouldShowProjectFilter"
      :filter="projectFilter"
      :data-testid="projectFilter.id"
      @filter-changed="updateFilterQuery"
    />
  </div>
</template>
