<template>
  <div v-if="common.active === 'notifications'" class="q-pb-md">
    <q-card class="no-shadow q-pb-md q-gutter-y-md q-mx-md">
      <div class="q-mx-md" v-if="!loading">
        <div class="q-py-md" v-if="notifications.length > 0">
          <BaseTable
            :hide-refresh="true"
            :columns="columns"
            :data="notifications"
            row-key="id"
            :title="$t('notifications.tableTitle')"
            :pagination.sync="pagination"
          >
            <template v-slot:body-item-active="props">
              <q-icon
                :name="props.row.active ? 'verified' : 'do_not_disturb'"
                size='20px'
                :class="props.row.active ? 'text-green' : 'text-red'"
              />
            </template>
          </BaseTable>
        </div>
        <q-card-section v-else>
          {{ $t('notifications.empty') }}
        </q-card-section>
        <q-btn
          class="q-mx-md q-mt-md"
          unelevated
          color="primary"
          :label="$t('notifications.edit')"
          type="button"
          @click="editDomainNotifications"
        />
      </div>
      <div style="padding: 200px" v-if="loading">
        <q-inner-loading :showing="loading">
          <q-spinner-gears color="primary" size="50px" />
        </q-inner-loading>
      </div>
    </q-card>
  </div>
</template>

<script lang="ts">
import isEqual from 'lodash/isEqual';
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 OrganizationNotificationsCard 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 loading = false;
  private eventsService = new EventsApi();

  @Watch('model', {
    immediate: true,
  })
  async modelWatcher(val: Notification, oldval: Notification) {
    if (val && !isEqual(val, oldval)) {
      this.loading = true;
      try {
        const notifications = await IdmServiceDomains.getDomainNotifications({
          id: val.id,
          expand: 'roles',
        });
        if (notifications.length) {
          Promise.allSettled(
            notifications.map((element: Notification) => {
              return this.eventsService.getEvent(element.eventId);
            })
          ).then((results: any) => {
            (results ?? []).forEach(
              (res: PromiseFulfilledResult<{data: {}, status: string}> | PromiseRejectedResult) => {
                if (res.status === 'fulfilled') {
                  this.eventList.push(res.value.data as Event);
                }
              }
            );
            this.loading = false;
          });
        } else {
          this.loading = false;
        }
        this.notifications = notifications;
      } 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',
        field: 'active',
        label: this.$t('notifications.active'),
        name: 'active',
        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);
  }
}
export default OrganizationNotificationsCard;
</script>
