<template>
  <div v-if="isActive">
    <q-card class="no-shadow q-pb-md q-gutter-y-md q-mx-md">
      <OrganisationsServicesTable :value="services" :loading="loading" />
      <q-btn
        v-if="isEditListOfServicesAllowed"
        @click="editListOfServices"
        :loading="editListOfServicesLoading"
        class="q-ml-lg q-mt-none"
        color="primary"
      >
        {{ $t('base.edit') }}
      </q-btn>
    </q-card>
  </div>
</template>

<script lang="ts">
import { Component, Prop, Mixins } from 'vue-property-decorator';
import OrganisationsServicesTable from './Services/Table.vue';
import { BaseCardCommon } from '@/interfaces';
import OrganizationService from '@services/entities/OrganizationService';
import Loadable from '@mixins/Loadable';
import { Organization } from '@interfaces/entities/Organization';
import { USER_SCOPES } from '@constants/entities/Scope';
import get from 'lodash/get';
import { Service } from '@openapi/registry-service';

@Component({
  components: {
    OrganisationsServicesTable,
  },
})
export default class OrganisationsServices extends Mixins(Loadable) {
  @Prop() common: BaseCardCommon;
  @Prop() model: { id: string };
  loading = false;
  editListOfServicesLoading = false;
  services: Service[] = [];

  get isActive(): boolean {
    return this.common.active === 'services';
  }

  get isEditListOfServicesAllowed(): boolean {
    return this.$AC.haveOneOfScope([
      USER_SCOPES.ORGANIZATION_ADMIN,
      USER_SCOPES.CLOUD_ADMIN,
    ]);
  }

  async editListOfServices(): Promise<void> {
    this.editListOfServicesLoading = true;
    const { traceId } = await this.$store.dispatch(
      'wf/processes/dispatchProcess',
      {
        processKey: 'LinkServicesToOrganization',
        data: {
          orgId: get(this.model, 'id'),
        },
      }
    );
    if (traceId) {
      const handler = (e: any) => {
        const data = JSON.parse(get(e, 'data', '{}'));
        if (data.traceId === traceId) {
          this.loading = false;
          this.$websockets.removeListener(handler);
        }
      };
      this.$websockets.addListener(handler);
    }
  }

  async fetchData(): Promise<void> {
    const id = this.model?.id ?? this.$route.params?.id;
    const { services = [] } = await this.withLoading<Organization>(() =>
      new OrganizationService().get(id, 'services')
    );
    this.services = services;
  }

  created(): void {
    this.fetchData();
  }
}
</script>
