<template>
  <div>
    <v-row>
      <v-col cols="12" sm="6" lg="4" xl="3">
        <v-select
          ref="ayaType"
          v-model="ayaType"
          :items="selectLists.coreAyaTypes"
          item-text="name"
          item-value="id"
          :label="$ay.t('AyaType')"
          data-cy="ayaType"
        ></v-select>
      </v-col>
      <v-col cols="12" sm="6" lg="4" xl="3">
        <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 && ayaType != 0"
          :loading="uploading"
          color="primary"
          text
          @click="upload"
          >{{ $ay.t("Upload") }}</v-btn
        >
      </v-col>

      <v-col cols="12">
        <v-textarea
          v-model="importResult"
          full-width
          readonly
          auto-grow
          data-cy="importResult"
        ></v-textarea>
      </v-col>
    </v-row>
  </div>
</template>
<script>
const FORM_KEY = "adm-import";
export default {
  data() {
    return {
      selectLists: {
        coreAyaTypes: []
      },
      uploadFiles: [],
      ayaType: 0,
      importResult: "",
      rights: window.$gz.role.defaultRightsObject(),
      uploading: false
    };
  },
  async created() {
    //NOTE:Global is what is checked for initialize to show this form and at server to allow import
    this.rights = window.$gz.role.getRights(window.$gz.type.Global);
    window.$gz.eventBus.$on("menu-click", clickHandler);
    await fetchTranslatedText(this);
    await populateSelectionLists(this);
    generateMenu(this);
  },
  beforeDestroy() {
    window.$gz.eventBus.$off("menu-click", clickHandler);
  },
  methods: {
    async upload() {
      //similar code in wiki-control
      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 = {
        ayaType: vm.ayaType,
        files: vm.uploadFiles,
        fileData: JSON.stringify(fileData)
      };
      try {
        vm.uploading = true;
        const res = await window.$gz.api.upload("import/upload", at);
        if (res.error) {
          window.$gz.errorHandler.handleFormError(res.error);
        } else {
          vm.uploadFiles = [];
          //result is an array of strings
          let outText = "";
          res.data.forEach(function appendImportResultItem(value) {
            outText += value + "\n";
          });
          vm.importResult = await window.$gz.translation.translateStringWithMultipleKeysAsync(
            outText
          );
        }
      } catch (error) {
        window.$gz.errorHandler.handleFormError(error);
      } finally {
        vm.uploading = false;
      }
    },
    handleSelected() {}
  }
};

/////////////////////////////
//
//
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: "$ayiFileImport",
    title: "Import",
    helpUrl: "adm-import",
    menuItems: []
  };

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

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

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