<template>
  <v-row v-if="this.formState.ready" v-resize="onResize">
    <gz-error :errorBoxMessage="formState.errorBoxMessage"></gz-error>
    <v-col cols="12" sm="6" lg="4" xl="3">
      <v-select
        v-model="selectedLog"
        :items="selectLists.serverLogs"
        item-text="logname"
        item-value="logname"
        :label="$ay.t('Log')"
        @input="logSelected"
        append-outer-icon="fa-sync"
        @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-6"
        >
          <pre>{{ log }}</pre>
        </v-card>
      </v-card>
    </v-col>
  </v-row>
</template>

<script>
/////////////////////////////////////////////////////////////////////////////////////////////////////////////
/*  Xeslint-disable    */
////////////////////////////////////////////////////////////////////////////////////////////////////////////

const FORM_KEY = "ops-logs";

export default {
  async created() {
    let vm = this;
    try {
      await initForm(vm);

      vm.formState.ready = true;
      window.$gz.eventBus.$on("menu-click", clickHandler);
      generateMenu(vm);
      vm.getDataFromApi();
      vm.formState.loading = false;
    } catch (err) {
      vm.formState.ready = true;
      window.$gz.errorHandler.handleFormError(err, vm);
    }
  },
  data() {
    return {
      log: null,
      selectedLog: "log-ayanova.txt",
      selectLists: {
        serverLogs: []
      },
      logCardHeight: 300,
      formState: {
        ready: false,
        loading: true,
        errorBoxMessage: null,
        appError: null,
        serverError: {}
      }
    };
  },
  beforeDestroy() {
    window.$gz.eventBus.$off("menu-click", clickHandler);
  },
  methods: {
    onResize() {
      this.logCardHeight = window.innerHeight * 0.7;
    },
    // 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);
      }
    },
    logSelected: function() {
      this.getDataFromApi();
    },
    async getDataFromApi() {
      let vm = this;
      if (!vm.selectedLog) {
        return;
      }
      vm.formState.loading = true;
      let url = "log-file/" + vm.selectedLog;
      window.$gz.form.deleteAllErrorBoxErrors(vm);
      try {
        let res = await window.$gz.api.get(url);

        if (res.error) {
          if (res.error.code == "2010") {
            window.$gz.eventBus.$emit("notify-error", vm.$ay.t("ErrorAPI2010"));
            window.$gz._.delay(function() {
              vm.$router.go(-1);
            }, 2000);
          }
          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
          });
          // generateMenu(vm);
        }
      } catch (error) {
        window.$gz.form.setFormState({
          vm: vm,
          loading: false
        });
        window.$gz.errorHandler.handleFormError(error, vm);
      }
    }
  }
};

//////////////////////
//
//
function generateMenu(vm) {
  let menuOptions = {
    isMain: true,
    icon: "fa-history",
    title: vm.$ay.t("ServerLog"),
    helpUrl: "form-ops-log",
    formData: {
      ayaType: window.$gz.type.LogFile
    },
    menuItems: [
      {
        title: vm.$ay.t("Copy"),
        icon: "fa-copy",
        surface: false,
        key: FORM_KEY + ":copylog",
        vm: vm
      }
    ]
  };

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

/////////////////////////////
//
//
function clickHandler(menuItem) {
  if (!menuItem) {
    return;
  }
  let 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;
      default:
        window.$gz.eventBus.$emit(
          "notify-warning",
          FORM_KEY + "::context click: [" + m.key + "]"
        );
    }
  }
}

/////////////////////////////////
//
//
function initForm(vm) {
  return new Promise(function(resolve, reject) {
    (async function() {
      try {
        await fetchTranslatedText(vm);
        await populateSelectionLists(vm);
      } catch (err) {
        reject(err);
      }
      resolve();
    })();
  });
}

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

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