<template>
  <v-row v-if="formState.ready" dense>
    <gz-error :error-box-message="formState.errorBoxMessage"></gz-error>
    <v-col cols="12">
      <v-btn class="mb-6" @click="getDataFromApi">
        <v-icon>$sockiSync</v-icon>
      </v-btn>
      <v-data-table
        dense
        :headers="headers"
        :items="obj"
        class="elevation-1"
        :disable-pagination="true"
        :disable-filtering="true"
        :disable-sort="true"
        hide-default-footer
        data-cy="jobsTable"
        :no-data-text="$sock.t('NoData')"
      >
        <template v-slot:[`item.actions`]="{ item }">
          <v-btn icon :href="item.url">
            <v-icon small class="mr-2">
              $sockiFileDownload
            </v-icon>
          </v-btn>
        </template></v-data-table
      >
    </v-col>
  </v-row>
</template>
<script>
const FORM_KEY = "ops-jobs";
export default {
  data() {
    return {
      obj: [],
      rawObj: [],
      formState: {
        ready: false,
        loading: true,
        errorBoxMessage: null,
        appError: null,
        serverError: {}
      },
      rights: window.$gz.role.defaultRightsObject(),
      timeZoneName: window.$gz.locale.getResolvedTimeZoneName(),
      languageName: window.$gz.locale.getResolvedLanguage(),
      hour12: window.$gz.locale.getHour12()
    };
  },
  async created() {
    const vm = this;
    try {
      await initForm(vm);
      vm.rights = window.$gz.role.getRights(window.$gz.type.ServerJob);
      vm.formState.readOnly = !vm.rights.change;
      vm.formState.ready = true;
      window.$gz.eventBus.$on("menu-click", clickHandler);
      await vm.getDataFromApi();
      vm.formState.loading = false;
    } catch (err) {
      vm.formState.ready = true;
      window.$gz.errorHandler.handleFormError(err, vm);
    }
  },
  beforeDestroy() {
    window.$gz.eventBus.$off("menu-click", clickHandler);
  },
  methods: {
    translation() {
      return window.$gz.translation;
    },
    locale() {
      return window.$gz.locale;
    },
    form() {
      return window.$gz.form;
    },
    fieldValueChanged(ref) {
      if (!this.formState.loading && !this.formState.readOnly) {
        window.$gz.form.fieldValueChanged(this, ref);
      }
    },
    async getDataFromApi() {
      const vm = this;
      vm.formState.loading = true;
      window.$gz.form.deleteAllErrorBoxErrors(vm);
      try {
        const res = await window.$gz.api.get("job-operations/logs/all-jobs");
        if (res.error) {
          if (res.error.code == "2010") {
            window.$gz.form.handleObjectNotFound(vm);
          }
          vm.formState.serverError = res.error;
          window.$gz.form.setErrorBoxErrors(vm);
        } else {
          if (res.data) {
            vm.rawObj = 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.utcDateToSpecifiedDateAndTimeLocalized(
                  o.created,
                  this.timeZoneName,
                  this.languageName,
                  this.hour12,
                  "short",
                  "medium"
                ),
                status: await window.$gz.translation.translateStringWithMultipleKeysAsync(
                  o.statusText
                ),
                jobId:
                  o.jobId == "00000000-0000-0000-0000-000000000000"
                    ? ""
                    : o.jobId
              });
            }
            vm.obj = ret;
          } else {
            vm.rawObj = [];
            vm.obj = [];
          }
          window.$gz.form.setFormState({
            vm: vm,
            dirty: false,
            valid: true,
            loading: false
          });
          generateMenu(vm);
        }
      } catch (error) {
        window.$gz.form.setFormState({
          vm: vm,
          loading: false
        });
        window.$gz.errorHandler.handleFormError(error, vm);
      }
    },
    async testJob() {
      const vm = this;
      vm.formState.loading = true;
      window.$gz.form.deleteAllErrorBoxErrors(vm);
      try {
        const res = await window.$gz.api.upsert("job-operations/test-job", {});
        vm.formState.loading = false;
        if (res.error) {
          vm.formState.serverError = res.error;
          window.$gz.form.setErrorBoxErrors(vm);
        }
      } catch (error) {
        vm.formState.loading = false;
        window.$gz.errorHandler.handleFormError(error, vm);
      }
    }
  }
};

//////////////////////
//
//
function generateMenu(vm) {
  const menuOptions = {
    isMain: true,
    readOnly: vm.formState.readOnly,
    icon: "$sockiRobot",
    title: "ServerJobs",
    helpUrl: "ops-jobs",
    formData: {
      sockType: window.$gz.type.ServerJob
    },
    menuItems: [
      {
        title: "Copy",
        icon: "$sockiCopy",
        surface: false,
        key: FORM_KEY + ":copylog",
        vm: vm
      }
    ]
  };

  if (vm.rights.change) {
    menuOptions.menuItems.push({
      title: "OpsTestJob",
      icon: "$sockiRobot",
      surface: false,
      key: FORM_KEY + ":TEST_JOB",
      vm: vm
    });
  }

  window.$gz.eventBus.$emit("menu-change", menuOptions);
}

/////////////////////////////
//
//
function clickHandler(menuItem) {
  if (!menuItem) {
    return;
  }
  const m = window.$gz.menu.parseMenuItem(menuItem);
  if (m.owner == FORM_KEY && !m.disabled) {
    switch (m.key) {
      case "copylog":
        //put the log info on the clipboard:
        window.$gz.util.copyToClipboard(
          "SERVER JOBS LOG\n" + JSON.stringify(m.vm.rawObj, null, 1)
        );
        break;
      case "TEST_JOB":
        m.vm.testJob();
        break;
      default:
        window.$gz.eventBus.$emit(
          "notify-warning",
          FORM_KEY + "::context click: [" + m.key + "]"
        );
    }
  }
}

/////////////////////////////////
//
//
async function initForm(vm) {
  await fetchTranslatedText();
  await createTableHeaders(vm);
}

//////////////////////////////////////////////////////////
//
// Ensures UI translated text is available
//
async function fetchTranslatedText() {
  await window.$gz.translation.cacheTranslations([
    "OpsTestJob",
    "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>
