<template>
  <v-dialog v-model="isVisible" persistent data-cy="extensions">
    <v-card>
      <v-card-title>{{ $sock.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">$sockiExclamationTriangle</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="$sock.t('NoData')"
            >
            </v-data-table>
          </div>
        </template>
        <v-expansion-panels focusable>
          <ExtensionTags :data-list-selection="dataListSelection" />
          <ExtensionExport :data-list-selection="dataListSelection" />
          <ExtensionDelete
            :data-list-selection="dataListSelection"
            @ext-close-refresh="close({ refresh: true })"
            @ext-show-job-log="handleError($event)"
          />
        </v-expansion-panels>
      </v-card-text>
      <v-card-actions>
        <v-btn text color="primary" @click="close()">{{
          $sock.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
  },
  data: () => ({
    isVisible: false,
    resolve: null,
    reject: null,
    dataListSelection: {
      SockType: 0,
      selectedRowIds: [],
      dataListKey: null
    },
    headers: [],
    errorObj: [],
    timeZoneName: window.$gz.locale.getResolvedTimeZoneName(),
    languageName: window.$gz.locale.getResolvedLanguage(),
    hour12: window.$gz.locale.getHour12()
  }),
  async created() {
    await initForm(this);
  },
  methods: {
    titleText() {
      if (this.dataListSelection.selectedRowIds.length < 1) {
        return this.$sock.t("AllItemsInList");
      }
      return `${this.$sock.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() {
  await window.$gz.translation.cacheTranslations(["TimeStamp", "ID", "Status"]);
}

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