<template>
  <div>
    <gz-data-table
      form-key="adm-translations"
      data-list-key="TranslationDataList"
      :show-select="false"
      :single-select="false"
      :reload="reload"
      data-cy="transTable"
    >
    </gz-data-table>
    <v-file-input
      v-model="uploadFiles"
      :label="$ay.t('Import')"
      accept="application/json"
      prepend-icon="$ayiFileUpload"
      multiple
      chips
    ></v-file-input>
    <v-btn
      v-if="uploadFiles.length > 0"
      :loading="uploading"
      color="primary"
      text
      @click="upload"
      >{{ $ay.t("Upload") }}</v-btn
    >
  </div>
</template>
<script>
const FORM_KEY = "adm-translations";
export default {
  data() {
    return {
      uploadFiles: [],
      rights: window.$gz.role.defaultRightsObject(),
      reload: false,
      uploading: false
    };
  },
  async created() {
    this.rights = window.$gz.role.getRights(window.$gz.type.Translation);
    window.$gz.eventBus.$on("menu-click", clickHandler);

    generateMenu(this);
  },
  beforeDestroy() {
    window.$gz.eventBus.$off("menu-click", clickHandler);
  },
  methods: {
    async upload() {
      const vm = this;
      const fileData = [];
      for (let i = 0; i < vm.uploadFiles.length; i++) {
        const f = vm.uploadFiles[i];
        fileData.push({ name: f.name, lastModified: f.lastModified });
      }
      const at = {
        ayaId: vm.ayaId,
        ayaType: vm.ayaType,
        files: vm.uploadFiles,
        fileData: JSON.stringify(fileData)
      };
      try {
        vm.uploading = true;
        const res = await window.$gz.api.upload("translation/upload", at);
        if (res.error) {
          window.$gz.errorHandler.handleFormError(res.error);
        } else {
          vm.uploadFiles = [];

          this.reload = !this.reload;
        }
      } catch (error) {
        window.$gz.errorHandler.handleFormError(error);
      } finally {
        vm.uploading = false;
      }
    }
  }
};

/////////////////////////////
//
//
function clickHandler(menuItem) {
  if (!menuItem) {
    return;
  }
  const m = window.$gz.menu.parseMenuItem(menuItem);
  if (m.owner == FORM_KEY && !m.disabled) {
    switch (m.key) {
      default:
        window.$gz.eventBus.$emit(
          "notify-warning",
          FORM_KEY + "::context click: [" + m.key + "]"
        );
    }
  }
}

//////////////////////
//
//
function generateMenu() {
  const menuOptions = {
    isMain: true,
    icon: "$ayiLanguage",
    title: "TranslationList",
    helpUrl: "adm-translations",
    menuItems: [],
    formData: {
      ayaType: window.$gz.type.Translation
    }
  };

  window.$gz.eventBus.$emit("menu-change", menuOptions);
}
</script>
