<script>
import vulnerabilitySeveritiesCountQuery from 'ee/security_dashboard/graphql/queries/vulnerability_severities_count.query.graphql';
import { DASHBOARD_TYPES } from 'ee/security_dashboard/store/constants';
import eventHub from 'ee/security_dashboard/utils/event_hub';
import VulnerabilityCountListLayout from './vulnerability_count_list_layout.vue';

export default {
  components: {
    VulnerabilityCountListLayout,
  },
  inject: ['dashboardType', 'groupFullPath', 'projectFullPath'],
  props: {
    filters: {
      type: Object,
      required: false,
      default: null,
    },
  },
  data() {
    return {
      queryError: false,
      vulnerabilitiesCount: {},
    };
  },
  computed: {
    isLoading() {
      return this.$apollo.queries.vulnerabilitiesCount.loading;
    },
    fullPath() {
      return this.groupFullPath || this.projectFullPath;
    },
  },
  created() {
    eventHub.$on('vulnerabilities-updated', () =>
      this.$apollo.queries.vulnerabilitiesCount.refetch(),
    );
  },
  apollo: {
    vulnerabilitiesCount: {
      query: vulnerabilitySeveritiesCountQuery,
      variables() {
        const { dashboardType, fullPath } = this;

        return {
          fullPath,
          isInstance: dashboardType === DASHBOARD_TYPES.INSTANCE,
          isGroup: dashboardType === DASHBOARD_TYPES.GROUP,
          isProject: dashboardType === DASHBOARD_TYPES.PROJECT,
          ...this.filters,
        };
      },
      update(data) {
        return data[this.dashboardType]?.vulnerabilitySeveritiesCount || {};
      },
      result() {
        this.queryError = false;
      },
      error() {
        this.queryError = true;
      },
      skip() {
        return !this.filters;
      },
    },
  },
};
</script>

<template>
  <vulnerability-count-list-layout
    :show-error="queryError"
    :is-loading="isLoading"
    :vulnerabilities-count="vulnerabilitiesCount"
  />
</template>
