<template>
  <div>
    <v-col cols="12" sm="6" lg="4" xl="3">
      <v-select
        v-model="ayaType"
        :items="selectLists.coreAyaTypes"
        item-text="name"
        item-value="id"
        :label="$ay.t('AyaType')"
        ref="ayaType"
        data-cy="ayaType"
      ></v-select>
    </v-col>
    <v-col>
      <v-file-input
        v-model="uploadFiles"
        :label="$ay.t('Import')"
        accept="application/json"
        prepend-icon="$ayiFile-upload"
        multiple
        chips
      ></v-file-input>
      <v-btn
        v-if="uploadFiles.length > 0 && ayaType != 0"
        :loading="uploading"
        color="primary"
        text
        @click="upload"
        >{{ $ay.t("Upload") }}</v-btn
      >
    </v-col>
    <v-col>
      <v-textarea
        v-model="importResult"
        full-width
        readonly
        auto-grow
        data-cy="importResult"
      ></v-textarea>
    </v-col>
  </div>
</template>

<script>
const FORM_KEY = "adm-import";
export default {
  async created() {
    this.rights = window.$gz.role.getRights(window.$gz.type.Translation);
    window.$gz.eventBus.$on("menu-click", clickHandler);
    await fetchTranslatedText(this);
    await populateSelectionLists(this);
    generateMenu(this);
  },
  beforeDestroy() {
    window.$gz.eventBus.$off("menu-click", clickHandler);
  },
  data() {
    return {
      selectLists: {
        coreAyaTypes: []
      },
      uploadFiles: [],
      ayaType: 0,
      importResult: "",
      rights: window.$gz.role.defaultRightsObject(),
      reload: false,
      uploading: false
    };
  },
  methods: {
    async upload() {
      //similar code in wiki-control
      let vm = this;
      let fileData = [];
      let importResult="";
      for (let i = 0; i < vm.uploadFiles.length; i++) {
        let f = vm.uploadFiles[i];
        fileData.push({ name: f.name, lastModified: f.lastModified });
      }
      let at = {
        ayaType: vm.ayaType,
        files: vm.uploadFiles,
        fileData: JSON.stringify(fileData)
      };
      try {
        vm.uploading = true;
        let res = await window.$gz.api.upload("import/upload", at);
        if (res.error) {
          window.$gz.errorHandler.handleFormError(res.error);
        } else {
          vm.uploadFiles = [];
          vm.importResult = res.data;
          this.reload = !this.reload;
        }
      } catch (error) {
        window.$gz.errorHandler.handleFormError(error);
      } finally {
        vm.uploading = false;
      }
    },
    handleSelected(selectedItems) {
      console.log(selectedItems);
    }
  }
};

/////////////////////////////
//
//
function clickHandler(menuItem) {
  if (!menuItem) {
    return;
  }
  let m = window.$gz.menu.parseMenuItem(menuItem);
  if (m.owner == FORM_KEY && !m.disabled) {
    switch (m.key) {
      // case "new":
      //   m.vm.$router.push({
      //     name: "adm-import",
      //     params: { recordid: 0 }
      //   });
      //   break;
      default:
        window.$gz.eventBus.$emit(
          "notify-warning",
          FORM_KEY + "::context click: [" + m.key + "]"
        );
    }
  }
}

//////////////////////
//
//
function generateMenu(vm) {
  let menuOptions = {
    isMain: true,
    icon: "$ayiFileImport",
    title: "Import",
    helpUrl: "form-adm-import",
    menuItems: []
  };

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

//////////////////////////////////////////////////////////
//
// Ensures UI translated text is available
//
async function fetchTranslatedText(vm) {
  await window.$gz.translation.cacheTranslations(["AyaType"]);
}

//////////////////////
//
//
async function populateSelectionLists(vm) {
  await window.$gz.enums.fetchEnumList("core");
  vm.selectLists.coreAyaTypes = window.$gz.enums.getSelectionList("core");
}
</script>
