<script>
import { isEqual } from 'lodash';
import { ALL, STATE } 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';
import { initFirstClassVulnerabilityFilters, mapProjects } from 'ee/security_dashboard/helpers';

export default {
  components: {
    DashboardFilter,
  },
  props: {
    projects: { type: Array, required: false, default: undefined },
  },
  data() {
    return {
      filters: initFirstClassVulnerabilityFilters(this.projects),
    };
  },
  computed: {
    selectedFilters() {
      return this.filters.reduce((acc, { id, selection }) => {
        if (!selection.has(ALL)) {
          acc[id] = Array.from(selection);
        }

        return acc;
      }, {});
    },
  },
  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)];
      }
    },

    '$route.query': {
      immediate: true,
      handler(newQuery) {
        let changed;

        this.filters.forEach((filter, i) => {
          let urlFilter = newQuery[filter.id];

          if (typeof urlFilter === 'undefined') {
            urlFilter = [ALL];
          } else if (!Array.isArray(urlFilter)) {
            urlFilter = [urlFilter];
          }

          if (isEqual(this.selectedFilters[filter.id], newQuery[filter.id]) === false) {
            changed = true;
            this.filters[i].selection = new Set(urlFilter);
          }
        });

        if (changed) {
          this.$emit('filterChange', this.selectedFilters);
        }
      },
    },
  },
  created() {
    if (Object.keys(this.selectedFilters).length === 0) {
      this.$router.push({ query: { state: [STATE.DETECTED, STATE.CONFIRMED] } });
    }
  },
  methods: {
    setFilter(options) {
      this.filters = setFilter(this.filters, options);
      this.$router.push({ query: this.selectedFilters });
      this.$emit('filterChange', this.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>
