<template>
  <v-row v-if="this.formState.ready">
    <gz-error :errorBoxMessage="formState.errorBoxMessage"></gz-error>
    <v-col cols="12">
      <v-select
        v-model="selectedLog"
        :items="selectLists.serverLogs"
        item-text="logname"
        item-value="logname"
        :label="$ay.t('Log')"
        @input="logSelected"
      >
      </v-select>
    </v-col>

    <v-col cols="12">
      <p class="title">{{ $ay.t("Log") }}</p>

      <v-btn @click="getDataFromApi" class="m-4">
        <v-icon>fa-sync</v-icon>
      </v-btn>
      <v-card style="overflow-x:scroll;" class="mt-6 pl-5 py-6">
        <pre>{{ log }}</pre>
        <!-- <v-textarea v-model="log" full-width readonly auto-grow></v-textarea> -->
      </v-card>
    </v-col>
  </v-row>
</template>

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

const FORM_KEY = "ops-logs";

export default {
  created() {
    let vm = this;
    initForm(vm)
      .then(() => {
        vm.formState.ready = true;
        window.$gz.eventBus.$on("menu-click", clickHandler);

        vm.formState.loading = false;
      })
      .catch(err => {
        vm.formState.ready = true;
        window.$gz.errorHandler.handleFormError(err, vm);
      });
  },
  data() {
    return {
      log: null,
      selectedLog: null,
      selectLists: {
        serverLogs: []
      },
      formState: {
        ready: false,
        loading: true,
        errorBoxMessage: null,
        appError: null,
        serverError: {}
      }
    };
  },
  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);
      }
    },
    logSelected: function() {
      this.getDataFromApi();
    },
    getDataFromApi() {
      let vm = this;
      if (!vm.selectedLog) {
        return;
      }
      vm.formState.loading = true;
      let url = "log-file/" + vm.selectedLog;
      window.$gz.form.deleteAllErrorBoxErrors(vm);
      window.$gz.api
        .get(url)
        .then(res => {
          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(function handleGetDataFromAPIError(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",
    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
//
function fetchTranslatedText(vm) {
  let tKeysRequired = ["OpsTestJob", "Log"];

  return window.$gz.translation.fetch(tKeysRequired);
}

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