/* eslint-disable @typescript-eslint/ban-ts-comment */
import { Component, Mixins, Vue } from 'vue-property-decorator';
import { oidcClientComputed } from '@state/modules/oidc-client';
import { fetchBaseReports } from '@services/document-registry';
import { notifyError } from '@utils/notify';
import { USER_SCOPES } from '@/constants/entities/Scope';
import { QBtn } from 'quasar';

const reports = Vue.extend({
  computed: {
    ...oidcClientComputed,
  },
});

@Component({})
export default class ReportsList extends Mixins(reports) {
  private reports: Record<string, any>[] = [];
  private loading = true;

  private pending = 0;

  created() {
    this.init();
  }

  updated(): void {
    this.$nextTick(() => {
      if (this.reports.length) {
        const from = this.$route.query?.from;
        if (from) {
          const active = this.$refs[Number(from)] as QBtn[];
          active[0].$el.classList.add('active_btn');
        }
      }
    });
  }

  private async fetch() {
    if (this.pending) {
      this.pending++;

      return;
    }
    this.pending = 1;

    try {
      this.reports = await fetchBaseReports().then((reports: any) =>
        reports.filter(
          (report: { scope?: USER_SCOPES[] }) =>
            !report.scope ||
            report.scope.some((role: USER_SCOPES) => this.$AC.haveScope(role))
        )
      );
    } catch (e) {
      notifyError(e.message.toString());
    } finally {
      this.loading = false;
    }

    if (this.pending > 1) {
      this.pending = 0;
      await this.fetch();

      return;
    }
    this.pending = 0;
  }

  private init() {
    return this.fetch();
  }
}
