<template>
  <modal ref="modal">
    <validator-group>
      <div class="modal-header">
        <h4 class="modal-title">Verwijderen</h4>
      </div>
      <div class="modal-body">
        <div class="form-check">
          <input class="form-check-input" type="radio" name="deleteRadio" id="deleteItem" :value="crudItemDeleteTypes.Item" v-model="crudItemDeleteType">
          <label class="form-check-label" for="deleteItem">Vertaling</label>
        </div>
        <p class="text-secondary">Je verwijderd de/het {{ name }} voor de vertaling {{ selectedLanguage.name }}</p>
        <div class="form-check">
          <input class="form-check-input" type="radio" name="deleteRadio" id="deleteAll" :value="crudItemDeleteTypes.All" v-model="crudItemDeleteType">
          <label class="form-check-label" for="deleteAll">{{ name }} en alle vertalingen</label>
        </div>
        <p class="text-secondary">Pas op! Hier verwijder je de/het {{ name }} en alle vertalingen.</p>
      </div>
      <div class="modal-footer">
        <button class="btn btn-light" @click.prevent="close">Annuleren</button>
        <submit :action="onDelete" button-type="danger">Verwijder</submit>
      </div>
    </validator-group>
  </modal>
</template>

<script lang="ts">
import { Vue, Component, Prop, Ref } from 'vue-property-decorator';
import { namespace } from 'vuex-class';

// @ts-ignore
import * as formElements from '../shared/form/all.js';
import Modal from '../shared/modal.vue';

import { SupportedLanguage } from '../types/language';
import { CrudStoreItemsModel } from '../stores/types/CrudStoreModel';
import RouteUtils, { createRoute, ROUTES } from '../tools/route-utils';

export enum CrudItemDeleteType {
  Item = 'item',
  All = 'all'
}

const LanguageStore = namespace('languages');
const AlertStore = namespace('alerts');

@Component({
  components: {
    Modal,
    ...formElements
  }
})
export default class DeletePageModal extends Vue {
  @Prop(Object) readonly item!: CrudStoreItemsModel;
  @Prop(String) readonly id!: string;
  @Prop(String) readonly module!: string;
  @Prop(String) readonly name!: string;

  @Ref() readonly modal: any;

  @LanguageStore.State('selected') selectedLanguage!: SupportedLanguage;
  @LanguageStore.Action('deleteItemTranslations') readonly deleteItemTranslations!: (languageRef: string) => Promise<void>;
  @AlertStore.Action('addError') readonly addError!: (message: string) => void;
  @AlertStore.Action('addSuccess') readonly addSuccess!: (message: string) => void;

  crudItemDeleteType = CrudItemDeleteType.Item;
  crudItemDeleteTypes = CrudItemDeleteType;

  open() {
    this.modal.show();
  }

  close() {
    this.modal.hide();
  }

  async onDelete() {
    try {
      switch(this.crudItemDeleteType) {
        case CrudItemDeleteType.Item:
          await this.handleItemDelete();
          break;
        case CrudItemDeleteType.All:
          await this.handleAllDelete();
          break;
      }

      this.$emit('delete');
    } catch (e) {
      this.$emit('error', e);
      await this.addError(`Verwijderen is niet gelukt! <br> ${e.message}`);
    } finally {
      this.close();
    }
  }

  async handleItemDelete() {
    if (!this.item) {
      throw new Error('No item to delete.');
    }

    await this.$store.dispatch(`${this.module}/deleteItem`, {
      id: this.id,
      item: this.item,
    });
    await this.$store.dispatch(`${this.module}/fetchCrudData`);
    await this.navigateToItemOverview();

    await this.addSuccess(`De/het ${this.name} is verwijderd verwijderd.`);
  }

  async handleAllDelete() {
    if (!this.item?.languageRef) {
      throw new Error('No language reference available to delete translations.');
    }

    await this.deleteItemTranslations(this.item.languageRef);
    await this.$store.dispatch(`${this.module}/fetchCrudData`);
    await this.navigateToItemOverview();

    await this.addSuccess(`De/het ${this.name} en alle vertalingen zijn verwijderd.`);
  }

  async navigateToItemOverview() {
    await RouteUtils.push(createRoute(ROUTES.CRUD_INDEX(this.module), null, { query: this.$route.query }));
  }
}
</script>
