<template>
  <v-expansion-panel v-if="available == true">
    <v-expansion-panel-header disable-icon-rotate expand-icon="$ayiTags">{{
      $ay.t("Tags")
    }}</v-expansion-panel-header>
    <v-expansion-panel-content>
      <v-radio-group v-model="action">
        <v-radio :label="$ay.t('Add')" value="Add"></v-radio>
        <v-radio :label="$ay.t('Remove')" value="Remove"></v-radio>
        <v-radio :label="$ay.t('Replace')" value="Replace"></v-radio>
      </v-radio-group>
      <v-row dense>
        <v-col cols="12">
          <v-text-field
            dense
            :value="tag"
            :label="$ay.t('Tag')"
            required
            @input="normalizeTag"
          ></v-text-field>
        </v-col>

        <v-col v-if="action == 'Replace'" cols="12">
          <v-text-field
            dense
            :value="replace"
            :label="$ay.t('Replace')"
            required
            @input="normalizeReplace"
          ></v-text-field>
        </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: () => ({
    action: "Add",
    tag: null,
    replace: null,
    jobActive: false,
    currentJobId: null,
    progress: "",
    rights: window.$gz.role.defaultRightsObject(),
    available: false
  }),
  created() {
    const vm = this;

    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-tags", "_blank");
    },
    canDoAction() {
      const vm = this;
      if (vm.action == "Replace" && !vm.replace) {
        return false;
      }
      if (vm.tag) {
        return true;
      }
      return false;
    },
    async requestCancel() {
      await window.$gz.api.upsert(
        "job-operations/request-cancel",
        this.currentJobId
      );
    },
    async doAction() {
      let url = "tag-list/";
      switch (this.action) {
        case "Add":
          url += `batch-add/${this.tag}`;
          break;
        case "Remove":
          url += `batch-remove/${this.tag}`;
          break;
        case "Replace":
          url += `batch-replace/${this.tag}?toTag=${this.replace}`;
          break;
      }

      try {
        this.progress = "";
        let jobId = await window.$gz.api.upsert(url, this.dataListSelection);
        if (jobId.error) {
          throw new Error(window.$gz.errorHandler.errorToString(jobId, this));
        }

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

        let jobProgress = {};
        while (this.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, this)
            );
          }
          jobProgress = jobProgress.data;
          this.progress = jobProgress.progress;

          if (jobProgress.jobStatus == 4 || jobProgress.jobStatus == 0) {
            throw new Error("Job failed");
          }
          if (jobProgress.jobStatus == 3) {
            this.jobActive = false;
          }
        }
        window.$gz.eventBus.$emit("notify-success", this.$ay.t("JobCompleted"));
      } catch (error) {
        this.jobActive = false;
        window.$gz.errorHandler.handleFormError(error, this);
        window.$gz.eventBus.$emit("notify-error", this.$ay.t("JobFailed"));
      }
    },
    normalize(value) {
      if (!value) {
        return null;
      }
      //Must be lowercase per rules
      //This may be naive when we get international customers but for now supporting utf-8 and it appears it's safe to do this with unicode
      value = value.toLowerCase();
      //No spaces in tags, replace with dashes
      value = value.split(" ").join("-");
      //Remove multiple dash sequences
      value = value.replace(/-+/g, "-");

      //Ensure doesn't start or end with a dash
      //linter says this is an unnecessary escape character so going with it but if issues with tag normalization here's maybe the culprit
      //value = value.replace(/^\-+-\-+$/g, "");
      value = value.replace(/^-+--+$/g, "");
      return value;
    },
    normalizeTag(value) {
      value = this.normalize(value);
      this.tag = value;
    },
    normalizeReplace(value) {
      value = this.normalize(value);
      this.replace = value;
    }
  }
};
</script>
