<template>
  <modal ref="modal">
    <validator-group>
      <div class="modal-header">
        <h4 class="modal-title">Verwijderen</h4>
      </div>
      <div class="modal-body">
        <template v-if="version && page.versions.length > 1">
          <div class="form-check">
            <input class="form-check-input" type="radio" name="deleteRadio" id="deleteVersion" :value="pageDeleteTypes.Version" v-model="pageDeleteType">
            <label class="form-check-label" for="deleteVersion">Versie</label>
          </div>
          <p class="text-secondary">{{ `Je verwijdert deze versie ${useMultiLanguage ? `voor de vertaling ${selectedLanguage.name}` : ''}.` }}</p>
        </template>
        <div class="form-check">
          <input class="form-check-input" type="radio" name="deleteRadio" id="deleteTranslation" :value="pageDeleteTypes.Page" v-model="pageDeleteType">
          <label class="form-check-label" for="deleteTranslation">{{ useMultiLanguage ? 'Vertaling' : 'Pagina' }}</label>
        </div>
        <p class="text-secondary">
          {{ useMultiLanguage ? `Je verwijdert alleen de vertaling ${selectedLanguage.name} voor deze pagina.` : 'Je verwijdert de hele pagina' }}
        </p>
        <multi-language-only>
          <div class="form-check">
            <input class="form-check-input" type="radio" name="deleteRadio" id="deletePage" :value="pageDeleteTypes.All" v-model="pageDeleteType">
            <label class="form-check-label" for="deletePage">Pagina en alle vertalingen</label>
          </div>
          <p class="text-secondary">Pas op! Hier verwijder je de pagina en alle vertalingen.</p>
        </multi-language-only>
      </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, 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 MultiLanguageOnly from '../shared/language/multi-language-only.vue';

import { SupportedLanguage } from '../types/language';
import { Version, VersionedPage } from '../types/api';
import RouteUtils, { createRoute, ROUTES } from '../tools/route-utils';

export enum PageDeleteType {
  Version = 'version',
  Page = 'page',
  All = 'all'
}

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

@Component({
  components: {
    MultiLanguageOnly,
    Modal,
    ...formElements
  }
})
export default class DeletePageModal extends Vue {
  @Ref() readonly modal: any;

  @LanguageStore.State('useMultiLanguage') useMultiLanguage!: boolean;
  @LanguageStore.State('selected') selectedLanguage!: SupportedLanguage;
  @LanguageStore.Action('deletePageTranslations') readonly deletePageTranslations!: (languageRef: string) => Promise<void>;
  @AlertStore.Action('addError') readonly addError!: (message: string) => void;
  @AlertStore.Action('addSuccess') readonly addSuccess!: (message: string) => void;
  @PageStore.Action('deleteVersion') readonly deleteVersion!: (version: Version) => Promise<boolean>;
  @PageStore.Action('delete') readonly delete!: (page: VersionedPage) => Promise<boolean>;

  page: VersionedPage | null = null;
  version: Version | null = null;
  pageDeleteType = PageDeleteType.Version;
  pageDeleteTypes = PageDeleteType;

  open(page: VersionedPage, version: Version) {
    this.page = page;
    this.version = version;
    this.pageDeleteType = version && page.versions.length > 1 ? PageDeleteType.Version : PageDeleteType.Page;

    this.modal.show();
  }

  close() {
    this.page = null;
    this.version = null;
    this.modal.hide();
  }

  async onDelete() {
    try {
      switch(this.pageDeleteType) {
        case PageDeleteType.Version:
          await this.handleVersionDelete();
          break;
        case PageDeleteType.Page:
          await this.handlePageDelete();
          break;
        case PageDeleteType.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 handleVersionDelete() {
    if (!this.version) {
      throw new Error('No active page version to delete.');
    }

    await this.deleteVersion(this.version);
    await RouteUtils.push(createRoute(ROUTES.PAGE_EDITOR, { id: this.page?.id || '' }))

    await this.addSuccess(`De versie is verwijderd.`);
  }

  async handlePageDelete() {
    if (!this.page) {
      throw new Error('No active page to delete.');
    }

    await this.delete(this.page);
    await RouteUtils.push(createRoute(ROUTES.PAGE_OVERVIEW));

    await this.addSuccess(`De pagina is verwijderd.`);
  }

  async handleAllDelete() {
    if (!this.useMultiLanguage) {
      return;
    }

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

    await this.deletePageTranslations(this.page.languageRef);
    await RouteUtils.push(createRoute(ROUTES.PAGE_OVERVIEW));

    await this.addSuccess(`De pagina en alle vertalingen zijn verwijderd.`);
  }
}
</script>
