<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-btn
        v-if="jobActive"
        color="red darken-1"
        text
        @click="requestCancel()"
      >
        {{ $ay.t("Cancel") }}</v-btn
      ><span v-if="jobActive">{{ progress }}</span>
    </v-expansion-panel-content>
  </v-expansion-panel>
</template>
<script>
export default {
  props: {
    dataListSelection: { type: Object, default: null }
  },
  data: () => ({
    jobActive: false,
    currentJobId: null,
    progress: "",
    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.dataListSelection.AType != window.$gz.type.PartInventoryDataList
    ) {
      vm.rights = window.$gz.role.getRights(vm.dataListSelection.AType);
    }
    vm.available = vm.rights.change;
  },
  methods: {
    goHelp() {
      window.open(window.$gz.api.helpUrl() + "ay-ex-delete", "_blank");
    },
    canDoAction() {
      return true;
    },
    async requestCancel() {
      await window.$gz.api.upsert(
        "job-operations/request-cancel",
        this.currentJobId
      );
    },
    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 {
        this.progress = "";
        //call api route
        let jobId = await window.$gz.api.upsert(url, body);
        if (jobId.error) {
          throw new Error(window.$gz.errorHandler.errorToString(jobId, vm));
        }

        this.currentJobId = jobId.jobId;
        vm.jobActive = true;

        let jobProgress = {};

        while (vm.jobActive == true) {
          await window.$gz.util.sleepAsync(2000);
          jobProgress = await window.$gz.api.get(
            `job-operations/progress/${this.currentJobId}`
          );
          if (jobProgress.error) {
            throw new Error(
              window.$gz.errorHandler.errorToString(jobProgress, vm)
            );
          }
          jobProgress = jobProgress.data;
          this.progress = jobProgress.progress;

          if (jobProgress.jobStatus == 4 || jobProgress.jobStatus == 0) {
            if (jobProgress.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 (jobProgress.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>
