<template>
  <div v-if="common.active === 'notifications' && !loading" class="q-pb-md">
    <q-card class="no-shadow q-pb-md q-gutter-y-md q-mx-md">
      <div class="q-mx-md">
        <div class="q-py-md" v-if="notifications.length > 0">
          <BaseTable
            :hide-refresh="true"
            :columns="columns"
            :data="notifications"
            :pagination.sync="pagination"
            row-key="id"
            :title="$t('notifications.tableTitle')"
          />
        </div>
        <q-btn
          class="q-mx-md q-mt-md"
          unelevated
          color="primary"
          :label="$t('notifications.edit')"
          type="button"
          @click="editDomainNotifications"
        />
      </div>
    </q-card>
  </div>
</template>

<script lang="ts">
import { Component, Prop, Vue, Watch } from 'vue-property-decorator';
import { BaseCardCommon } from '@interfaces/components';
import { Notification } from '@openapi/idm';
import QColumn from '@/types/QColumn';
import { TablePagination } from '@models/base/TablePagination';
import IdmServiceDomains from '@services/idm/domains';
import { Event, EventsApi } from '@openapi/notifier-registry';
import { notifyError } from '@utils/notify';

@Component({})
class RegionNotificationsCard extends Vue {
  @Prop({}) private common?: BaseCardCommon;
  @Prop({}) private model?: Notification;

  private pagination = new TablePagination({ rowsPerPage: 5 });
  private notifications: Array<Notification> = [];
  private eventList: Array<Event> = [];
  private eventsService = new EventsApi();

  @Watch('model', {
    immediate: true,
  })
  async modelWatcher(val: Notification, oldVal: Notification) {
    if (val && val !== oldVal) {
      try {
        this.notifications = await IdmServiceDomains.getDomainNotifications({
          id: val.id,
          expand: 'roles',
        });
        await this.notifications.forEach(async (element: any) => {
          const event = await this.eventsService
            .getEvent(element.eventId)
            .then((response) => response.data);
          this.eventList.push(event);
        });
      } catch (e) {
        notifyError(e.message.toString());
      }
    }
  }

  private get columns(): Array<QColumn> {
    return [
      {
        align: 'left',
        field: (i: any) => i,
        handler: (val: any) => {
          this.$router.push({
            name: 'cards',
            params: {
              id: val?.id,
              path: 'notifications',
            },
            query: {
              components: this.$store.getters[
                'cardComponents/notifications/components'
              ],
              active: 'settings',
            },
          });
        },
        formatField: 'title',
        label: this.$t('notifications.name'),
        name: 'title',
        style: 'white-space: normal;',
        required: true,
        sortable: true,
      },
      {
        align: 'left',
        label: this.$t('notifications.role'),
        field: 'roles',
        formatField: 'displayName',
        defaultFormatField: 'name',
        name: 'roles',
        icon: 'o_group',
        required: true,
        sortable: true,
      },
      {
        align: 'left',
        field: (val: any) =>
          this.eventList.find((event) => event.id === val.eventId)?.description,
        label: this.$t('notifications.event'),
        name: 'event',
        required: true,
        sortable: true,
      },
    ];
  }

  editDomainNotifications(): void {
    this.$store.dispatch('wf/processes/dispatchProcess', {
      processKey: 'ConnectNotificationsToDomainProcess',
      data: {
        domainId: this.model?.id,
      },
    });
    this.$store.commit('idm/notifications/notificationCardLoading', true);
  }

  private get loading(): string {
    return this.$store.getters['domainId/services/notificationCardLoading'];
  }
}
export default RegionNotificationsCard;
</script>
