<script>
import { initFirstClassVulnerabilityFilters, mapProjects } from 'ee/security_dashboard/helpers';
import { ALL } from 'ee/security_dashboard/store/modules/filters/constants';
import { setFilter } from 'ee/security_dashboard/store/modules/filters/utils';
import DashboardFilter from 'ee/security_dashboard/components/filter.vue';

export default {
  components: {
    DashboardFilter,
  },
  props: {
    projects: { type: Array, required: false, default: undefined },
  },
  data() {
    return {
      filters: initFirstClassVulnerabilityFilters(this.projects),
    };
  },
  watch: {
    /**
     * Initially the project list empty. We fetch them dynamically from GraphQL while
     * fetching the list of vulnerabilities. We display the project filter with the base
     * option and when the projects are fetched we add them to the list.
     */
    projects(newProjects, oldProjects) {
      if (oldProjects.length === 0) {
        const projectFilter = this.filters[3];
        projectFilter.options = [projectFilter.options[0], ...mapProjects(this.projects)];
      }
    },
  },
  methods: {
    setFilter(options) {
      const selectedFilters = {};
      this.filters = setFilter(this.filters, options);

      this.filters.forEach(({ id, selection }) => {
        if (!selection.has(ALL)) {
          selectedFilters[id] = Array.from(selection);
        }
      });

      this.$emit('filterChange', selectedFilters);
    },
  },
};
</script>

<template>
  <div class="dashboard-filters border-bottom bg-gray-light">
    <div class="row mx-0 p-2">
      <dashboard-filter
        v-for="filter in filters"
        :key="filter.id"
        class="col-sm-6 col-md-4 col-lg-2 p-2"
        :filter="filter"
        @setFilter="setFilter"
      />
    </div>
  </div>
</template>
