<template>
  <div v-if="initialized">
    <editor-translations :type="entityType" :translations="translations" @click="switchTranslation" />
    <template v-if="hasTranslatableLanguages">
      <button class="btn btn-light btn-block" @click="addPageTranslationModal.open()">Vertaling toevoegen</button>
      <add-page-translation-modal
        :translations="translations"
        :translatable-languages="translatableLanguages"
        :language-ref="languageRef"
        :version-id="versionId"
        :page-id="pageId"
        ref="addPageTranslationModal"
        @add="handleAdd" />
    </template>
  </div>
</template>

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

import AddPageTranslationModal from './add-page-translation-modal.vue';
import EntityTranslationsProvider from './entity-translations-provider.vue';
import EditorTranslations from './editor-translations.vue';
import { EntityType, PageTranslation, SupportedLanguage } from '../../types/language';
import { Route } from 'vue-router';
import { RawLocation } from 'vue-router/types/router';
import LanguageApi from '../../api/language-api';
import RouteUtils, { createRoute, ROUTES } from '../../tools/route-utils';

const LanguageStore = namespace('languages');

@Component({
  components: {
    AddPageTranslationModal,
    EntityTranslationsProvider,
    EditorTranslations
  }
})
export default class PageEditorTranslations extends EntityTranslationsProvider<PageTranslation> {
  @Prop(String) readonly languageRef!: string;
  @Prop(String) readonly versionId!: string;
  @Prop(String) readonly pageId!: string;

  entityType = EntityType.Page;

  @Ref() readonly addPageTranslationModal!: AddPageTranslationModal;

  @LanguageStore.State('all') readonly allLanguages!: SupportedLanguage[];

  async beforeMount() {
    await this.initialize(() => LanguageApi.getPageTranslations(this.languageRef));

    if (!this.getTranslationByKey(this.selectedLanguage.key)?.pageId) {
      await RouteUtils.replace(this.emptyStateRoute);
    }
  }

  switchTranslation(translation: PageTranslation) {
    const language = this.allLanguages.find(language => language.key === translation.language);

    if (language && this.selectedLanguage !== language) {
      translation.pageId
        ? this.setSelectedLanguage(language)
        : this.addPageTranslationModal.open(translation.language)
    }
  }

  async handlePageTranslationSwitch(to: Route, from: Route, next: (to?: RawLocation | false) => void) {
    if (to.params.lang !== from.params.lang) {
      const currentTranslation = this.translations.find(translation => translation.language === from.params.lang);
      const translation = this.translations.find(translation => translation.language === to.params.lang);

      if (!translation || !currentTranslation) {
        next();
        return;
      }

      // PageId of null means the page is not translated and therefore we should redirect to the empty state
      if (!translation.pageId) {
        // Current page is the empty state so another redirect would be a duplicate, unnecessary route push
        if (!currentTranslation.pageId) {
          next();
          return;
        }

        next(this.emptyStateRoute);
        // If the target route already has the corresponding translation pageId skip, otherwise redirect to the page editor with correct id
      } else if (translation.pageId !== to.params.id) {
        next(createRoute(ROUTES.PAGE_EDITOR, { id: translation.pageId, lang: translation.language }));
      } else {
        next();
      }
    } else {
      next();
    }
  }

  async handleAdd(language: SupportedLanguage) {
    await this.update(language);

    const translation = this.getTranslationByKey(language.key);
    if (this.$route.name === 'page-editor-empty-translation' && translation?.pageId) {
      await RouteUtils.replace(createRoute(ROUTES.PAGE_EDITOR, { id: translation.pageId, lang: translation.language }));
    }
  }

  get emptyStateRoute() {
    return createRoute(ROUTES.PAGE_EDITOR_EMPTY_TRANSLATION, { languageRef: this.languageRef }, {
      query: { versionId: this.versionId }
    });
  }

  get translatableLanguages() {
    return this.allLanguages.filter(language => !this.translations.some(translation => translation.language === language.key && translation.pageId));
  }

  get hasTranslatableLanguages() {
    return this.translatableLanguages.length > 0;
  }
}
</script>
