<template>
  <v-row v-if="formState.ready" v-resize="onResize" dense>
    <gz-error :error-box-message="formState.errorBoxMessage"></gz-error>
    <v-col cols="12" sm="6" lg="4" xl="3">
      <v-select
        v-model="selectedLog"
        dense
        :items="selectLists.serverLogs"
        item-text="logname"
        item-value="logname"
        :label="$ay.t('Log')"
        append-outer-icon="$ayiSync"
        data-cy="selectedLog"
        @input="logSelected"
        @click:append-outer="getDataFromApi"
      >
      </v-select>
    </v-col>
    <v-col cols="12">
      <v-card elevation="4">
        <v-card
          :height="logCardHeight"
          style="overflow:auto;"
          class="pl-5 py-4"
        >
          <pre>{{ log }}</pre>
        </v-card>
      </v-card>
    </v-col>
  </v-row>
</template>
<script>
const FORM_KEY = "ops-logs";
export default {
  data() {
    return {
      log: null,
      selectedLog: "log-ayanova.txt",
      selectLists: {
        serverLogs: []
      },
      logCardHeight: 300,
      formState: {
        ready: false,
        loading: true,
        errorBoxMessage: null,
        appError: null,
        serverError: {}
      }
    };
  },
  async created() {
    const vm = this;
    try {
      await initForm(vm);
      vm.formState.ready = true;
      window.$gz.eventBus.$on("menu-click", clickHandler);
      generateMenu(vm);
      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: {
    onResize() {
      this.logCardHeight = window.innerHeight * 0.8;
    },
    form() {
      return window.$gz.form;
    },
    fieldValueChanged(ref) {
      if (!this.formState.loading && !this.formState.readOnly) {
        window.$gz.form.fieldValueChanged(this, ref);
      }
    },
    logSelected: function() {
      this.getDataFromApi();
    },
    downloadLog() {
      const vm = this;
      if (!vm.selectedLog) {
        return;
      }
      try {
        const href = window.$gz.api.genericDownloadUrl(
          "log-file/download/" + vm.selectedLog
        );
        if (window.open(href, "DownloadLog") == null) {
          throw new Error(
            "Unable to download, your browser rejected navigating to download url."
          );
        }
      } catch (error) {
        window.$gz.errorHandler.handleFormError(error, this);
        // window.$gz.eventBus.$emit("notify-error", this.$ay.t("JobFailed"));
      }
    },

    async getDataFromApi() {
      const vm = this;
      if (!vm.selectedLog) {
        return;
      }
      vm.formState.loading = true;
      window.$gz.form.deleteAllErrorBoxErrors(vm);
      try {
        const res = await window.$gz.api.get("log-file/" + vm.selectedLog);
        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) {
            vm.log = res;
          } else {
            vm.log = vm.$ay.t("NoData");
          }
          window.$gz.form.setFormState({
            vm: vm,
            dirty: false,
            valid: true,
            loading: false
          });
        }
      } catch (error) {
        window.$gz.form.setFormState({
          vm: vm,
          loading: false
        });
        window.$gz.errorHandler.handleFormError(error, vm);
      }
    }
  }
};

//////////////////////
//
//
function generateMenu(vm) {
  const menuOptions = {
    isMain: true,
    icon: "$ayiHistory",
    title: "ServerLog",
    helpUrl: "ops-log",
    formData: {
      ayaType: window.$gz.type.LogFile
    },
    menuItems: [
      {
        title: "Copy",
        icon: "$ayiCopy",
        surface: false,
        key: FORM_KEY + ":copylog",
        vm: vm
      },
      {
        title: "Download",
        icon: "$ayiFileDownload",
        key: FORM_KEY + ":download",
        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 LOG\n" + m.vm.log);
        break;
      case "download":
        m.vm.downloadLog();
        break;
      case "copyFullTechSupportInfo":
        m.vm.copyFullTechSupportInfo();
        break;
      default:
        window.$gz.eventBus.$emit(
          "notify-warning",
          FORM_KEY + "::context click: [" + m.key + "]"
        );
    }
  }
}

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

//////////////////////////////////////////////////////////
//
// Ensures UI translated text is available
//
async function fetchTranslatedText() {
  await window.$gz.translation.cacheTranslations([
    "OpsTestJob",
    "Log",
    "Download",
    "CopySupportInfo"
  ]);
}

//////////////////////
//
//
async function populateSelectionLists(vm) {
  let res = await window.$gz.api.get("log-file");
  if (res.error) {
    vm.formState.serverError = res.error;
    window.$gz.form.setErrorBoxErrors(vm);
  } else {
    vm.selectLists.serverLogs = res.data;
  }
}
</script>
