<template>
  <v-row v-if="formState.ready" dense>
    <gz-error :error-box-message="formState.errorBoxMessage"></gz-error>
    <v-col>
      <v-card id="ayaNovaVersioncard" data-cy="versionCard">
        <v-subheader>AyaNova App</v-subheader>
        <div>
          <span class="ml-6 text-body-1">{{ $ay.t("Version") }}: </span>
          <span class="text-body-2">{{ clientInfo.version }}</span>
        </div>
        <div>
          <span class="ml-6 text-body-1">{{ $ay.t("User") }}: </span>
          <span class="text-body-2">{{ $store.state.userName }}</span>
        </div>

        <div>
          <span class="ml-6 text-body-1">12h: </span>
          <span class="text-body-2">
            {{ locale().getHour12() }}
          </span>
        </div>

        <div>
          <span class="ml-6 text-body-1">Effective time zone: </span>
          <span class="text-body-2">
            {{ locale().getResolvedTimeZoneName() }}
          </span>
        </div>

        <div>
          <span class="ml-6 text-body-1">Effective language code: </span>
          <span class="text-body-2">{{ locale().getResolvedLanguage() }}</span>
        </div>

        <div>
          <span class="ml-6 text-body-1"
            >{{ $ay.t("NativeDateTimeInput") }}:
          </span>
          <span class="text-body-2">{{
            $store.state.nativeDateTimeInput
          }}</span>
        </div>

        <div>
          <span class="ml-6 text-body-1">{{ $ay.t("CurrencyCode") }}: </span>
          <span class="text-body-2">{{ locale().getCurrencyName() }}</span>
        </div>

        <div>
          <span class="ml-6 text-body-1">{{ $ay.t("DarkMode") }}: </span>
          <span class="text-body-2">{{ $store.state.darkMode }}</span>
        </div>

        <v-divider class="mt-6"></v-divider>
        <v-subheader>{{ $ay.t("Browser") }}</v-subheader>
        <div v-for="(value, name) in browser" :key="name">
          <span class="ml-6 text-body-1">{{ name }}: </span>
          <span class="text-body-2">{{ value }}</span>
        </div>

        <v-divider class="mt-6"></v-divider>
        <v-subheader>{{ $ay.t("Server") }}</v-subheader>
        <div>
          <span class="ml-6 text-body-1">{{ $ay.t("ServerAddress") }}: </span>
          <span class="text-body-2">{{ apiUrl }}</span>
        </div>
        <div>
          <span class="ml-6 text-body-1">{{ $ay.t("Version") }}: </span>
          <span class="text-body-2"
            >{{ serverInfo.serverVersion }}&nbsp;{{ serverInfo.build }}</span
          >
        </div>
        <div>
          <span class="ml-6 text-body-1">{{ $ay.t("SchemaVersion") }}: </span>
          <span class="text-body-2">{{ serverInfo.dbSchemaVersion }}</span>
        </div>
        <div>
          <span class="ml-6 text-body-1">{{ $ay.t("ServerTime") }}: </span>
          <span class="text-body-2">{{ serverInfo.serverLocalTime }}</span>
        </div>
        <div>
          <span class="ml-6 text-body-1">Server time zone: </span>
          <span class="text-body-2">{{ serverInfo.serverTimeZone }}</span>
        </div>
        <div v-if="canViewLicenseInfo()">
          <v-divider class="mt-6"></v-divider>
          <v-subheader>{{ $ay.t("HelpLicense") }}</v-subheader>
          <div>
            <span class="ml-6 text-body-1"
              >{{ $ay.t("RegisteredUser") }}:
            </span>
            <span class="text-body-2">{{
              serverInfo.license.license.licensedTo
            }}</span>
          </div>
          <div>
            <span class="ml-6 text-body-1">{{ $ay.t("DatabaseID") }}: </span>
            <span class="text-body-2">{{
              serverInfo.license.license.serverDbId
            }}</span>
          </div>
          <div>
            <span class="ml-6 text-body-1">{{ $ay.t("LicenseSerial") }}: </span>
            <span class="text-body-2">{{
              serverInfo.license.license.keySerial
            }}</span>
          </div>
          <div>
            <span class="ml-6 text-body-1">{{ $ay.t("LicenseType") }}: </span>
            <span class="text-body-2">{{
              serverInfo.license.license.perpetual
                ? $ay.t("LicenseTypePerpetual")
                : $ay.t("LicenseTypeSubscription")
            }}</span>
          </div>
          <div>
            <span class="ml-6 text-body-1"
              >{{ $ay.t("LicenseExpiration") }}:
            </span>
            <span class="text-body-2">{{
              $ay.dt(serverInfo.license.license.licenseExpiration)
            }}</span>
          </div>
          <div>
            <span class="ml-6 text-body-1"
              >{{ $ay.t("SupportedUntil") }}:
            </span>
            <span class="text-body-2">{{
              $ay.dt(serverInfo.license.license.maintenanceExpiration)
            }}</span>
          </div>

          <v-divider class="mt-6"></v-divider>
          <v-subheader data-cy="aboutlicensedoptions">{{
            $ay.t("LicensedOptions")
          }}</v-subheader>

          <div
            v-for="item in serverInfo.license.license.features"
            :key="item.Feature"
          >
            <span class="ml-6 text-body-1">{{ item.Feature }}</span>
            <span class="text-body-2">{{
              item.Count ? ": " + item.Count : ""
            }}</span>
          </div>
        </div>

        <v-divider class="mt-6"></v-divider>
      </v-card>
    </v-col>
  </v-row>
</template>
<script>
import ayaNovaVersion from "../api/ayanova-version";
export default {
  data() {
    return {
      serverInfo: { license: { license: {} } },
      clientInfo: {},
      browser: {},
      formState: {
        ready: false,
        loading: true,
        errorBoxMessage: null,
        appError: null,
        serverError: {}
      }
    };
  },
  computed: {
    apiUrl() {
      return window.$gz.api.APIUrl("");
    }
  },
  async created() {
    const vm = this;
    try {
      await initForm(vm);
      vm.formState.ready = true;
      window.$gz.eventBus.$on("menu-click", clickHandler);
      generateMenu(vm);
      vm.formState.loading = false;
    } catch (err) {
      vm.formState.ready = true;
      window.$gz.errorHandler.handleFormError(err, vm);
    }
  },
  beforeDestroy() {
    window.$gz.eventBus.$off("menu-click", clickHandler);
  },
  mounted() {
    this.clientInfo = {};
    this.clientInfo = ayaNovaVersion;
  },
  methods: {
    translation() {
      return window.$gz.translation;
    },
    locale() {
      return window.$gz.locale;
    },
    canViewLicenseInfo() {
      return (
        window.$gz.store.state.userType == 1 ||
        window.$gz.store.state.userType == 2
      );
    }
  }
};

//////////////////////
//
//
function generateMenu(vm) {
  const menuOptions = {
    isMain: false,
    icon: "$ayiInfoCircle",
    title: "HelpAboutAyaNova",
    helpUrl: "ay-about",
    menuItems: [
      {
        title: "CopyToClipboard",
        icon: "$ayiCopy",
        key: "about:copy",
        vm: vm
      },
      {
        title: "Log",
        icon: "$ayiGlasses",
        key: "app:nav:log",
        data: "ay-log"
      }
    ]
  };
  if (!window.$gz.store.getters.isCustomerUser) {
    menuOptions.menuItems.push({
      title: "HelpTechSupport",
      icon: "$ayiLifeRing",
      href: window.$gz.menu.contactSupportUrl(),
      target: "_blank",
      key: "about:contact"
    });

    menuOptions.menuItems.push({
      title: "ViewEULA",
      key: "about:eula"
    });
  }

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

/////////////////////////////
//
//
function clickHandler(menuItem) {
  if (!menuItem) {
    return;
  }
  const m = window.$gz.menu.parseMenuItem(menuItem);
  if (m.owner == "about" && !m.disabled) {
    switch (m.key) {
      case "contact":
        break;
      case "eula":
        if (!window.$gz.store.state.globalSettings.sBuild) {
          window.$gz.eventBus.$emit("menu-click", {
            key: "app:help",
            data: "license"
          });
        } else {
          window.$gz.eventBus.$emit("menu-click", {
            key: "app:help",
            data: "ayanova-subscription-service-agreement"
          });
        }
        break;
      case "copy":
        //put the support info on the clipboard:
        {
          const element = document.getElementById("ayaNovaVersioncard");
          const text = element.innerText || element.textContent;
          let logText = "";
          m.vm.$store.state.logArray.forEach(function appendLogItem(value) {
            logText += value + "\n";
          });
          window.$gz.util.copyToClipboard(text + "\nCLIENT LOG\n" + logText);
        }
        break;
      default:
        window.$gz.eventBus.$emit(
          "notify-warning",
          "About.vue::context click: [" + m.key + "]"
        );
    }
  }
}

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

//////////////////////////////////////////////////////////
//
// Ensures UI translated text is available
//
async function fetchTranslatedText() {
  await window.$gz.translation.cacheTranslations([
    "HelpAboutAyaNova",
    "HelpTechSupport",
    "Server",
    "Version",
    "SchemaVersion",
    "ServerTime",
    "ServerAddress",
    "TimeZone",
    "HelpLicense",
    "RegisteredUser",
    "DatabaseID",
    "LicenseSerial",
    "LicenseExpiration",
    "SupportedUntil",
    "LicensedOptions",
    "Log",
    "User",
    "Browser",
    "LanguageCode",
    "CurrencyCode",
    "ViewEULA",
    "DarkMode",
    "NativeDateTimeInput",
    "LicenseType",
    "LicenseTypeSubscription",
    "LicenseTypePerpetual"
  ]);
}

////////////////////
//
async function getServerInfo(vm) {
  const res = await window.$gz.api.get("server-info");
  if (!Object.prototype.hasOwnProperty.call(res, "data")) {
    return Promise.reject(res);
  } else {
    vm.serverInfo = res.data;
  }
}

////////////////////
//
function getBrowserInfo(vm) {
  vm.browser = {
    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
  };
}

//eoc
</script>
