<template>
  <v-row v-if="formState.ready" align="start" justify="center">
    <gz-error :error-box-message="formState.errorBoxMessage"></gz-error>
    <v-col cols="12" md="7">
      <v-card id="ayaNovaConfigCard" data-cy="configCard">
        <v-subheader>AyaNova server settings</v-subheader>
        <v-list two-line>
          <v-list-item>
            <v-list-item-content>
              <v-list-item-title>AYANOVA_DEFAULT_TRANSLATION</v-list-item-title>
              <v-list-item-subtitle class="text-wrap">{{
                config.ayanovA_DEFAULT_TRANSLATION
              }}</v-list-item-subtitle>
            </v-list-item-content>
          </v-list-item>

          <v-list-item>
            <v-list-item-content>
              <v-list-item-title>AYANOVA_USE_URLS</v-list-item-title>
              <v-list-item-subtitle class="text-wrap">{{
                config.ayanovA_USE_URLS
              }}</v-list-item-subtitle>
            </v-list-item-content>
          </v-list-item>

          <v-list-item>
            <v-list-item-content>
              <v-list-item-title>AYANOVA_DB_CONNECTION</v-list-item-title>
              <v-list-item-subtitle class="text-wrap">{{
                config.ayanovA_DB_CONNECTION
              }}</v-list-item-subtitle>
            </v-list-item-content>
          </v-list-item>

          <v-list-item>
            <v-list-item-content>
              <v-list-item-title
                >AYANOVA_REPORT_RENDERING_TIMEOUT</v-list-item-title
              >
              <v-list-item-subtitle class="text-wrap">{{
                config.ayanovA_REPORT_RENDERING_TIMEOUT
              }}</v-list-item-subtitle>
            </v-list-item-content>
          </v-list-item>

          <v-list-item>
            <v-list-item-content>
              <v-list-item-title
                >AYANOVA_ATTACHMENT_FILES_PATH</v-list-item-title
              >
              <v-list-item-subtitle class="text-wrap">{{
                config.ayanovA_ATTACHMENT_FILES_PATH
              }}</v-list-item-subtitle>
            </v-list-item-content>
          </v-list-item>

          <v-list-item>
            <v-list-item-content>
              <v-list-item-title>AYANOVA_BACKUP_FILES_PATH</v-list-item-title>
              <v-list-item-subtitle class="text-wrap">{{
                config.ayanovA_BACKUP_FILES_PATH
              }}</v-list-item-subtitle>
            </v-list-item-content>
          </v-list-item>

          <v-list-item>
            <v-list-item-content>
              <v-list-item-title>AYANOVA_TEMP_FILES_PATH</v-list-item-title>
              <v-list-item-subtitle class="text-wrap">{{
                config.ayanovA_TEMP_FILES_PATH
              }}</v-list-item-subtitle>
            </v-list-item-content>
          </v-list-item>

          <v-list-item>
            <v-list-item-content>
              <v-list-item-title>AYANOVA_BACKUP_PG_DUMP_PATH</v-list-item-title>
              <v-list-item-subtitle class="text-wrap">{{
                config.ayanovA_BACKUP_PG_DUMP_PATH
              }}</v-list-item-subtitle>
            </v-list-item-content>
          </v-list-item>

          <v-list-item>
            <v-list-item-content>
              <v-list-item-title>AYANOVA_LOG_PATH</v-list-item-title>
              <v-list-item-subtitle class="text-wrap">{{
                config.ayanovA_LOG_PATH
              }}</v-list-item-subtitle>
            </v-list-item-content>
          </v-list-item>

          <v-list-item>
            <v-list-item-content>
              <v-list-item-title>AYANOVA_LOG_LEVEL</v-list-item-title>
              <v-list-item-subtitle class="text-wrap">{{
                config.ayanovA_LOG_LEVEL
              }}</v-list-item-subtitle>
            </v-list-item-content>
          </v-list-item>

          <v-list-item>
            <v-list-item-content>
              <v-list-item-title class="text-wrap"
                >AYANOVA_LOG_ENABLE_LOGGER_DIAGNOSTIC_LOG</v-list-item-title
              >
              <v-list-item-subtitle class="text-wrap">{{
                config.ayanovA_LOG_ENABLE_LOGGER_DIAGNOSTIC_LOG
              }}</v-list-item-subtitle>
            </v-list-item-content>
          </v-list-item>

          <div>
            <v-divider class="mt-6"></v-divider>
            <v-subheader>Server Environment</v-subheader>
            <div v-for="(value, name, index) in config.serverinfo" :key="index">
              <span class="ml-6 body-1">{{ name }}: </span>
              <span class="body-2">{{ value }}</span>
            </div>
          </div>
          <div>
            <v-divider class="mt-6"></v-divider>
            <v-subheader>DB Server parameters</v-subheader>
            <div
              v-for="(value, name, index) in config.dbserverinfo"
              :key="index"
            >
              <span class="ml-6 body-1">{{ name }}: </span>
              <span class="body-2">{{ value }}</span>
            </div>
          </div>
        </v-list>
      </v-card>
    </v-col>
  </v-row>
</template>
<script>
const FORM_KEY = "ops-view-configuration";
export default {
  data() {
    return {
      config: {},
      formState: {
        ready: false,
        loading: true,
        errorBoxMessage: null,
        appError: null,
        serverError: {}
      }
    };
  },
  async created() {
    const vm = this;
    try {
      await fetchTranslatedText();
      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: {
    async copyFullTechSupportInfo() {
      const vm = this;
      window.$gz.form.deleteAllErrorBoxErrors(vm);

      try {
        const serverSupportInfoResponse = await window.$gz.api.get(
          "server-state/tech-support-info"
        );
        if (serverSupportInfoResponse.error) {
          if (serverSupportInfoResponse.error.code == "2010") {
            window.$gz.form.handleObjectNotFound(vm);
          }
          vm.formState.serverError = serverSupportInfoResponse.error;
          window.$gz.form.setErrorBoxErrors(vm);
        } else {
          if (serverSupportInfoResponse) {
            const browserInfo = {
              platform: window.navigator.platform,
              userAgent: window.navigator.userAgent,
              languages: window.navigator.languages,
              tz: Intl.DateTimeFormat().resolvedOptions().timeZone,
              oscpu: window.navigator.oscpu,
              maxTouchPoints: window.navigator.maxTouchPoints,
              webdriver: window.navigator.webdriver,
              vendor: window.navigator.vendor,
              availWidth: window.screen.availWidth,
              availHeight: window.screen.availHeight,
              width: window.screen.width,
              height: window.screen.height,
              devicePixelRatio: window.devicePixelRatio,
              pixelDepth: window.screen.pixelDepth
            };

            let logText = "";
            this.$store.state.logArray.forEach(function appendLogItem(value) {
              logText += value + "\n";
            });

            window.$gz.util.copyToClipboard(
              `#########################################################\nCLIENT BROWSER INFO\n${JSON.stringify(
                browserInfo
              )}\n#########################################################\nCLIENT ERROR LOG\n${logText}\n${
                serverSupportInfoResponse.data
              }`
            );
            //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);
      }
    },
    async getDataFromApi() {
      const vm = this;
      vm.formState.loading = true;
      window.$gz.form.deleteAllErrorBoxErrors(vm);
      try {
        const res = await window.$gz.api.get(
          "server-state/active-configuration"
        );
        if (res.error) {
          vm.formState.serverError = res.error;
          window.$gz.form.setErrorBoxErrors(vm);
        } else {
          vm.config = res.data;
          window.$gz.form.setFormState({
            vm: vm,
            dirty: false,
            valid: true,
            loading: false
          });
        }
      } catch (error) {
        window.$gz.errorHandler.handleFormError(error, vm);
      } finally {
        window.$gz.form.setFormState({
          vm: vm,
          loading: false
        });
      }
    }
  }
};

//////////////////////
//
//
function generateMenu(vm) {
  const menuOptions = {
    isMain: true,
    icon: "$ayiInfoCircle",
    title: "ViewServerConfiguration",
    helpUrl: "ops-server-information",
    menuItems: [
      {
        title: "CopySupportInfo",
        icon: "$ayiCopy",
        key: FORM_KEY + ":copyFullTechSupportInfo",
        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 "copyFullTechSupportInfo":
        m.vm.copyFullTechSupportInfo();
        break;
      default:
        window.$gz.eventBus.$emit(
          "notify-warning",
          FORM_KEY + "::context click: [" + m.key + "]"
        );
    }
  }
}

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