<template>
  <v-row v-if="formState.ready" dense>
    <gz-error :error-box-message="formState.errorBoxMessage"></gz-error>
    <v-col>
      <v-card id="sockeyeVersioncard" data-cy="versionCard">
        <v-subheader>Sockeye App</v-subheader>
        <div>
          <span class="ml-6 text-body-1">{{ $sock.t("Version") }}: </span>
          <span class="text-body-2">{{ clientInfo.version }}</span>
        </div>
        <div>
          <span class="ml-6 text-body-1">{{ $sock.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"
            >{{ $sock.t("NativeDateTimeInput") }}:
          </span>
          <span class="text-body-2">{{
            $store.state.nativeDateTimeInput
          }}</span>
        </div>

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

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

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

          <v-divider class="mt-6"></v-divider>
          <v-subheader data-cy="aboutlicensedoptions">{{
            $sock.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 sockeyeVersion from "../api/sockeye-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 = sockeyeVersion;
  },
  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: "$sockiInfoCircle",
    title: "HelpAboutSockeye",
    helpUrl: "sock-about",
    menuItems: [
      {
        title: "CopyToClipboard",
        icon: "$sockiCopy",
        key: "about:copy",
        vm: vm
      },
      {
        title: "Log",
        icon: "$sockiGlasses",
        key: "app:nav:log",
        data: "sock-log"
      }
    ]
  };
  if (!window.$gz.store.getters.isCustomerUser) {
    menuOptions.menuItems.push({
      title: "HelpTechSupport",
      icon: "$sockiLifeRing",
      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("sockeyeVersioncard");
          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([
    "HelpAboutSockeye",
    "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>
