<template>
  <v-expansion-panel v-if="available == true">
    <v-expansion-panel-header disable-icon-rotate expand-icon="$ayiTrashAlt">{{
      $ay.t("Delete")
    }}</v-expansion-panel-header>
    <v-expansion-panel-content>
      <v-row>
        <v-col cols="12">
          <v-icon x-large color="accent">$ayiSkullCrossbones</v-icon>
        </v-col>
      </v-row>

      <v-btn icon @click="goHelp()"><v-icon>$ayiQuestionCircle</v-icon></v-btn>
      <v-btn
        :disabled="!canDoAction()"
        color="blue darken-1"
        text
        :loading="jobActive"
        @click="doAction()"
        >{{ $ay.t("StartJob") }}</v-btn
      >
    </v-expansion-panel-content>
  </v-expansion-panel>
</template>
<script>
export default {
  props: {
    dataListSelection: { type: Object, default: null }
  },
  data: () => ({
    jobActive: false,
    rights: window.$gz.role.defaultRightsObject(),
    available: false
  }),
  async created() {
    const vm = this;
    await fetchTranslatedText();
    //NOTE: if extension doesn't support a particular object add it here to the NoType default
    if (
      vm.dataListSelection.AType != 0 &&
      vm.dataListSelection.AType != window.$gz.type.PartInventoryRestock
    ) {
      vm.rights = window.$gz.role.getRights(vm.dataListSelection.AType);
    }
    vm.available = vm.rights.change;
  },
  methods: {
    goHelp() {
      window.open(this.$store.state.helpUrl + "ay-ex-delete", "_blank");
    },
    canDoAction() {
      return true;
    },
    async doAction() {
      const vm = this;
      const dialogResult = await window.$gz.dialog.confirmGeneric(
        "EraseMultipleObjectsWarning",
        "error"
      );
      if (dialogResult == false) {
        return;
      }
      //Clear any possible prior errors
      vm.$emit("ext-show-job-log", "clear");

      //do the batch action
      const url = "job-operations/batch-delete";
      const body = this.dataListSelection;

      try {
        //call api route
        let jobId = await window.$gz.api.upsert(url, body);
        if (jobId.error) {
          throw new Error(window.$gz.errorHandler.errorToString(jobId, vm));
        }
        jobId = jobId.jobId; //it's in a sub key
        //indicate loading by setting on button
        vm.jobActive = true;

        let jobStatus = 1;

        while (vm.jobActive == true) {
          await window.$gz.util.sleepAsync(1000);
          //check if done
          jobStatus = await window.$gz.api.get(
            `job-operations/status/${jobId}`
          );
          if (jobStatus.error) {
            throw new Error(
              window.$gz.errorHandler.errorToString(jobStatus, vm)
            );
          }
          jobStatus = jobStatus.data;
          if (jobStatus == 4 || jobStatus == 0) {
            if (jobStatus == 4) {
              //emit job id and event to parent for log viewing
              vm.$emit("ext-show-job-log", jobId);
            }
            throw new Error("Job failed");
          }
          if (jobStatus == 3) {
            vm.jobActive = false;
          }
        }
        //Here if it's completed successfully
        window.$gz.eventBus.$emit("notify-success", vm.$ay.t("JobCompleted"));
        vm.$emit("ext-close-refresh");
      } catch (error) {
        vm.jobActive = false;
        window.$gz.eventBus.$emit("notify-error", vm.$ay.t("JobFailed"));
      }
    }
  }
};

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