<template>
  <v-dialog v-model="isVisible" persistent data-cy="extensions">
    <v-card>
      <v-card-title>{{ $ay.t("Extensions") }}</v-card-title>
      <v-card-subtitle class="mt-1">{{ titleText() }}</v-card-subtitle>
      <v-card-text>
        <template v-if="errorObj.length > 0">
          <div class="mt-4 mb-8">
            <v-icon large color="error">$ayiExclamationTriangle</v-icon>
            <v-data-table
              dense
              :headers="headers"
              :items="errorObj"
              class="elevation-4"
              :disable-pagination="true"
              :disable-filtering="true"
              hide-default-footer
              hide-default-header
              :no-data-text="$ay.t('NoData')"
            >
            </v-data-table>
          </div>
        </template>
        <v-expansion-panels focusable>
          <ExtensionTags :data-list-selection="dataListSelection" />
          <ExtensionExport :data-list-selection="dataListSelection" />
          <ExtensionDelete
            @ext-close-refresh="close({ refresh: true })"
            @ext-show-job-log="handleError($event)"
            :data-list-selection="dataListSelection"
          />
        </v-expansion-panels>
      </v-card-text>
      <v-card-actions>
        <v-btn text @click="close()" color="primary">{{
          $ay.t("Close")
        }}</v-btn>
      </v-card-actions>
    </v-card>
  </v-dialog>
</template>
<script>
import ExtensionTags from "./extension-tags-control.vue";
import ExtensionExport from "./extension-export-control.vue";
import ExtensionDelete from "./extension-delete-control.vue";

export default {
  components: {
    ExtensionTags,
    ExtensionExport,
    ExtensionDelete
  },
  async created() {
    await initForm(this);
  },
  data: () => ({
    isVisible: false,
    resolve: null,
    reject: null,
    dataListSelection: {
      AType: 0,
      selectedRowIds: [],
      dataListKey: null
    },
    headers: [],
    errorObj: [],
    timeZoneName: window.$gz.locale.getResolvedTimeZoneName(),
    languageName: window.$gz.locale.getResolvedLanguage(),
    hour12: window.$gz.locale.getHour12()
  }),
  methods: {
    titleText() {
      if (this.dataListSelection.selectedRowIds.length < 1) {
        return this.$ay.t("AllItemsInList");
      }
      return `${this.$ay.t("SelectedItems")} ${
        this.dataListSelection.selectedRowIds.length
      }`;
    },
    async handleError(jobId) {
      if (!jobId || jobId == "00000000-0000-0000-0000-000000000000") {
        throw "Error: extension triggered handleError with empty jobId";
      }

      if (jobId == "clear") {
        this.errorObj = [];
        return;
      }

      const res = await window.$gz.api.get(`job-operations/logs/${jobId}`);
      if (res.data) {
        const ret = [];
        for (let i = 0; i < res.data.length; i++) {
          const o = res.data[i];
          ret.push({
            id: i,
            created: window.$gz.locale.utcDateToShortDateAndTimeLocalized(
              o.created,
              this.timeZoneName,
              this.languageName,
              this.hour12
            ),
            status: await window.$gz.translation.translateStringWithMultipleKeysAsync(
              o.statusText
            ),
            jobId:
              o.jobId == "00000000-0000-0000-0000-000000000000" ? "" : o.jobId
          });
        }

        this.errorObj = ret;
      } else {
        this.errorObj = [];
      }
    },
    open(dls) {
      this.errorObj = [];
      this.dataListSelection = dls;
      this.isVisible = true;
      return new Promise((resolve, reject) => {
        this.resolve = resolve;
        this.reject = reject;
      });
    },
    close(ret) {
      this.isVisible = false;
      this.errorObj = [];
      this.resolve(ret);
    }
  }
};
/////////////////////////////////
//
//
async function initForm(vm) {
  await fetchTranslatedText(vm);
  await createTableHeaders(vm);
}

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

//////////////////////
//
//
async function createTableHeaders(vm) {
  vm.headers = [
    { text: vm.$ay.t("TimeStamp"), value: "created" },
    { text: vm.$ay.t("Status"), value: "status" },
    { text: vm.$ay.t("ID"), value: "jobId" }
  ];
}
</script>
