<template>
  <div v-if="common.active === 'settings' && !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="cardModel">
          <base-label-value class="q-pa-xs q-gutter-x-md">
            <template #label>
              {{ $t('notifications.name') }}
            </template>

            <template #value>
              {{ cardModel.title }}
            </template>
          </base-label-value>
          <base-label-value
            v-if="cardModel.roles"
            class="q-pa-xs q-gutter-x-md"
          >
            <template #label>
              {{ $t('notifications.role') }}
            </template>
            <template #value>
              <div
                v-for="(item, index) in cardModel.roles"
                :key="`role-${index}`"
                class="q-pb-xs"
              >
                {{ item.shortname || item.displayName }}
              </div>
            </template>
          </base-label-value>
          <base-label-value v-if="regions" class="q-pa-xs q-gutter-x-md">
            <template #label>
              {{ $t('notifications.regions') }}
            </template>
            <template #value>
              <q-chip
                v-for="(region, index) in regions.slice(0, 3)"
                :key="`region-${index}`"
              >
                {{ region }}
              </q-chip>
              <q-chip
                v-if="regions.slice(3).length"
                clickable
                outline
                @click="showRegions(regions.slice(3))"
              >
                ...
                {{
                  $t('notifications.more', {
                    length: regions.slice(3).length,
                  })
                }}
              </q-chip>
            </template>
          </base-label-value>
          <base-label-value class="q-pa-xs q-gutter-x-md" v-if="event">
            <template #label>
              {{ $t('notifications.event') }}
            </template>

            <template #value>
              {{ event.description }}
            </template>
          </base-label-value>
        </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, GraphApi } from '@openapi/idm';
import { Event, EventsApi } from '@openapi/notifier-registry';
import { notifyError } from '@utils/notify';

const graphApi = new GraphApi();

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

  private cardModel: Notification | null = null;
  private event: Event | null = null;
  private regions: Array<string> = [];
  private eventsService = new EventsApi();

  @Watch('model', {
    immediate: true,
  })
  async modelWatcher(val: Notification) {
    if (val) {
      try {
        this.cardModel = val;
        if (val.eventId) {
          this.event = await this.eventsService
            .getEvent(val.eventId)
            .then((response) => response.data);
        }
        const regions = ((await graphApi
          .flatten(
            'Notification',
            'incoming',
            [val.id],
            1,
            ['Region'],
            undefined,
            ['Account:person']
          )
          .then(({ data }) => data)
          .catch(() => {
            throw new Error('[components][cards][notifications][graphApi]');
          })) as unknown) as Document[];

        this.regions = (regions ?? []).map((i: any) => i.fullname);
      } catch (e) {
        notifyError(e.message.toString());
      }
    }
  }

  private showRegions(regions: Array<string>): void {
    this.$q.dialog({
      message: regions.join(', '),
    });
  }

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

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