<i18n>
{
  "en": {
    "ResourceCard": {
      "yes": "Yes",
      "no": "No",
      "delete": "Delete",
      "edit": "Edit",
      "questionToDelete": "Are you sure you want to delete the resource?",
      "confirmation": "Confirmation",
      "enabled": "Enabled",
      "id": "Resource ID",
      "description": "Resource description",
      "operationId": "Operation ID",
      "path": "Path",
      "title": "General info"
    }
  },
  "ru": {
    "ResourceCard": {
      "yes": "Да",
      "no": "Нет",
      "delete": "Удалить",
      "edit": "Редактировать",
      "questionToDelete": "Вы действительно хотите удалить ресурс?",
      "confirmation": "Подтвердите",
      "enabled": "Включен",
      "id": "Идентификатор ресурса",
      "description": "Описание ресурса",
      "operationId": "Идентификатор операции",
      "path": "Путь",
      "title": "Основные данные"
    }
  }
}
</i18n>
<template>
  <div>
    <q-card class="bg-grey-custom no-shadow q-gutter-y-md q-mx-md q-mt-md">
      <div
        class="rounded-borders bg-white items-center justify-between row q-pa-md"
      >
        <div class="text-h6 flex items-center text-grey-9 col q-pr-md">
          <q-btn
            padding="xs"
            class="text-grey-7 q-mr-md"
            color="grey-3"
            icon="arrow_back"
            @click="backToResources"
          />
          <span class="text-h5">{{ title }}</span>
        </div>
        <div class="center row-md">
          <div class="justify-end flex">
            <q-btn
              color="white"
              text-color="primary"
              class="q-mr-md"
              outline
              :label="$t('ResourceCard.delete')"
              type="button"
              @click="dialogDelete = true"
            />
            <q-btn
              disable
              unelevated
              color="primary"
              :label="$t('ResourceCard.edit')"
              type="button"
            />
          </div>
        </div>
      </div>
    </q-card>

    <base-tabs v-if="!loading" :current-tab="tabs.current" :tabs="tabs.list" />

    <q-dialog v-model="dialogDelete">
      <q-card class="no-shadow">
        <q-card-section>
          <div class="text-h6">{{ $t('ResourceCard.confirmation') }}</div>
        </q-card-section>

        <q-card-section class="q-pt-none">
          {{ $t('ResourceCard.questionToDelete') }}
        </q-card-section>

        <q-card-actions align="right">
          <q-btn
            flat
            :label="$t('ResourceCard.no')"
            color="primary"
            @click="dialogDelete = false"
          />
          <q-btn
            flat
            :label="$t('ResourceCard.yes')"
            color="red"
            @click="deleteResource"
          />
        </q-card-actions>
      </q-card>
    </q-dialog>
    <q-page-sticky
      class="lt-sm q-py-md"
      position="bottom-right"
      :offset="[16, 0]"
    >
      <div>
        <q-btn
          text-color="primary"
          class="q-mr-sm bg-white"
          outline
          icon="delete"
          round
          type="button"
          @click="dialogDelete = true"
        />
        <q-btn
          unelevated
          color="primary"
          icon="edit"
          round
          disable
          type="button"
        />
      </div>
    </q-page-sticky>
  </div>
</template>

<script lang="ts">
import { Component, Prop, Vue, Watch } from 'vue-property-decorator';
import { BaseCardCommon } from '@/interfaces';
import { CardNeedToUpdateType } from '@constants/models/Card';

@Component({})
export default class ResourcesCardIndex extends Vue {
  @Prop({}) private common?: BaseCardCommon;
  @Prop({}) private model?: any;

  private loading = false;
  private dialogDelete = false;
  private id = '';
  private path = '';
  private tabs = {
    current: 'basic',
    list: [
      {
        name: this.$t('ResourceCard.title'),
        path: 'basic',
        visible: true,
      },
    ],
  };

  @Watch('model', {
    immediate: true,
  })
  registryWatcher(val: any) {
    if (val) {
      this.id = val.id;
      this.path = val.path;
    }
  }

  @Watch('common.active', {
    immediate: true,
  })
  activeWatcher(val: any) {
    this.tabs.current = val;
  }

  @Watch('common.needToUpdate', {
    immediate: true,
  })
  updateWatcher(val: any) {
    this.$store.commit(`utils/cards/needToUpdate`, CardNeedToUpdateType.FALSE);
    this.init(val);
  }

  private get title() {
    const title = this.path || String(this.$t('ResourceCard.title'));

    if (!title) {
      return title;
    }

    return title[0].toUpperCase() + title.slice(1);
  }

  private created() {
    this.initModel();
  }

  private backToResources() {
    this.$router.push({
      path: '/resources',
    });
  }

  private deleteResource(e: any) {
    this.dialogDelete = false;
    this.$store.dispatch('wf/processes/dispatchProcess', {
      processKey: 'DeleteAndNotifyResourcesIDMProcess',
      data: {
        resourceIds: [this.id],
        redirectUrl: '/resources',
      },
    });

    this.$emit('showLoading', e);
  }

  private init(needToUpdateType = CardNeedToUpdateType.TRUE) {
    this.initModel();
    // global
    switch (needToUpdateType) {
      case CardNeedToUpdateType.TRUE: {
        this.initModel();
        break;
      }
      // optional
      case CardNeedToUpdateType.MODEL: {
        this.initModel();
        break;
      }
    }
  }

  private initModel() {
    return new Promise((resolve, reject) => {
      try {
        this.$store
          .dispatch('idm/resources/dispatchResource', {
            id: this?.common?.id,
          })
          .then((model) => {
            this.$store.commit(`utils/cards/addModel`, {
              model,
              path: this?.common?.path,
            });
            return resolve();
          })
          .catch((e) => reject(e));
      } catch (e) {
        return reject(e);
      }
    });
  }

  private beforeDestroy() {
    this.$store.commit(`utils/cards/removeModel`, {
      path: this?.common?.path,
    });

    this.$store.commit(`utils/cards/removeUserTask`, {
      path: this?.common?.path,
    });
  }
}
</script>
