<template>
  <v-row v-if="this.formState.ready">
    <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 body-1">{{ $ay.t("Version") }}: </span>
          <span class="body-2">{{ clientInfo.version }}</span>
        </div>
        <div>
          <span class="ml-6 body-1">{{ $ay.t("User") }}: </span>
          <span class="body-2">{{ this.$store.state.userName }}</span>
        </div>

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

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

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

        <div>
          <span class="ml-6 body-1">{{ $ay.t("CurrencyCode") }}: </span>
          <span class="body-2">{{ locale().getCurrencyName() }}</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 body-1">{{ name }}: </span>
          <span class="body-2">{{ value }}</span>
        </div>

        <v-divider class="mt-6"></v-divider>
        <v-subheader>{{ $ay.t("Server") }}</v-subheader>
        <div>
          <span class="ml-6 body-1">{{ $ay.t("ServerAddress") }}: </span>
          <span class="body-2">{{ this.$store.state.apiUrl }}</span>
        </div>
        <div>
          <span class="ml-6 body-1">{{ $ay.t("Version") }}: </span>
          <span class="body-2">{{ serverInfo.serverVersion }}</span>
        </div>
        <div>
          <span class="ml-6 body-1">{{ $ay.t("SchemaVersion") }}: </span>
          <span class="body-2">{{ serverInfo.dbSchemaVersion }}</span>
        </div>
        <div>
          <span class="ml-6 body-1">{{ $ay.t("ServerTime") }}: </span>
          <span class="body-2">{{ serverInfo.serverLocalTime }}</span>
        </div>
        <div>
          <span class="ml-6 body-1">{{ $ay.t("TimeZone") }}: </span>
          <span class="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 body-1">{{ $ay.t("RegisteredUser") }}: </span>
            <span class="body-2">{{
              serverInfo.license.license.licensedTo
            }}</span>
          </div>
          <div>
            <span class="ml-6 body-1">{{ $ay.t("DatabaseID") }}: </span>
            <span class="body-2">{{
              serverInfo.license.license.serverDbId
            }}</span>
          </div>
          <div>
            <span class="ml-6 body-1">{{ $ay.t("LicenseSerial") }}: </span>
            <span class="body-2">{{
              serverInfo.license.license.keySerial
            }}</span>
          </div>
          <div>
            <span class="ml-6 body-1">{{ $ay.t("LicenseExpiration") }}: </span>
            <span class="body-2">{{
              serverInfo.license.license.licenseExpiration
            }}</span>
          </div>
          <div>
            <span class="ml-6 body-1">{{ $ay.t("SupportedUntil") }}: </span>
            <span class="body-2">{{
              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 body-1">{{ item.Feature }}</span>
            <span class="body-2">{{
              item.Count ? ": " + item.Count : ""
            }}</span>
          </div>
        </div>

        <v-divider class="mt-6"></v-divider>
      </v-card>
    </v-col>
  </v-row>
</template>

<script>
/* xeslint-disable */
import ayaNovaVersion from "../api/ayanova-version";

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.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;
  },
  data() {
    return {
      serverInfo: { license: { license: {} } },
      clientInfo: {},
      browser: {},
      formState: {
        ready: false,
        loading: true,
        errorBoxMessage: null,
        appError: null,
        serverError: {}
      }
    };
  },
  methods: {
    translation() {
      return window.$gz.translation;
    },
    locale() {
      return window.$gz.locale;
    },
    canViewLicenseInfo() {
      /*
       Administrator = 1,
        Schedulable = 2,
        NonSchedulable = 3,
        Customer = 4,
        HeadOffice = 5,
        Utility = 6,        Subcontractor = 7 */
      return (
        window.$gz.store.state.userType == 1 ||
        window.$gz.store.state.userType == 2 ||
        window.$gz.store.state.userType == 3
      );
    }
  }
};

//////////////////////
//
//
function generateMenu(vm) {
  let menuOptions = {
    isMain: false,
    icon: "$ayiInfoCircle",
    title: "HelpAboutAyaNova",
    helpUrl: "ay-about",
    menuItems: [
      {
        title: "CopySupportInfo",
        icon: "$ayiCopy",
        key: "about:copysupportinfo",
        vm: vm
      },
      {
        title: "Log",
        icon: "$ayiGlasses",
        key: "app:nav:log",
        data: "ay-log"
      },
      {
        title: "HelpTechSupport",
        icon: "$ayiLifeRing",
        href: window.$gz.menu.contactSupportUrl(),
        target: "_blank",
        key: "about:contact"
      }
    ]
  };

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

/////////////////////////////
//
//
function clickHandler(menuItem) {
  if (!menuItem) {
    return;
  }
  let m = window.$gz.menu.parseMenuItem(menuItem);
  if (m.owner == "about" && !m.disabled) {
    switch (m.key) {
      case "contact":
        break;
      case "copysupportinfo":
        //put the support info on the clipboard:
        let element = document.getElementById("ayaNovaVersioncard");
        let text = element.innerText || element.textContent;

        let logText = "";
        //de-lodash
        // window.$gz. _.forEach(m.vm.$store.state.logArray, function appendLogItem(
        //   value
        // ) {
        //   logText += value + "\n";
        // });

        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(vm);
  await getServerInfo(vm);
  await getBrowserInfo(vm);
}

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

////////////////////
//
async function getServerInfo(vm) {
  let res = await window.$gz.api.get("server-info");
  //We never expect there to be no data here
  if (!res.hasOwnProperty("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>
