<template>
  <v-row v-if="formState.ready" dense>
    <gz-error :error-box-message="formState.errorBoxMessage"></gz-error>
    <v-col>
      <v-form ref="form" data-cy="licenseForm">
        <v-row dense align="start" justify="center">
          <template v-if="showLicenseUi() == 'ok'">
            <!-- Normal active license UI -->
            <v-col cols="12" md="7">
              <v-card>
                <v-list dense two-line subheader>
                  <v-subheader>{{ $ay.t("HelpLicense") }}</v-subheader>

                  <v-list-item dense>
                    <v-list-item-content>
                      <v-list-item-title>{{
                        $ay.t("RegisteredUser")
                      }}</v-list-item-title>
                      <v-list-item-subtitle class="text-wrap">{{
                        currentLicenseInfo.licensedTo
                      }}</v-list-item-subtitle>
                    </v-list-item-content>
                  </v-list-item>

                  <v-list-item dense>
                    <v-list-item-content>
                      <v-list-item-title>{{
                        $ay.t("DatabaseID")
                      }}</v-list-item-title>
                      <v-list-item-subtitle class="text-wrap">{{
                        currentLicenseInfo.serverDbId
                      }}</v-list-item-subtitle>
                    </v-list-item-content>
                  </v-list-item>

                  <v-list-item dense>
                    <v-list-item-content>
                      <v-list-item-title>
                        {{ $ay.t("LicenseSerial") }}</v-list-item-title
                      >
                      <v-list-item-subtitle class="text-wrap">{{
                        currentLicenseInfo.keySerial
                      }}</v-list-item-subtitle>
                    </v-list-item-content>
                  </v-list-item>

                  <v-list-item dense>
                    <v-list-item-content>
                      <v-list-item-title>{{
                        $ay.t("LicenseType")
                      }}</v-list-item-title>
                      <v-list-item-subtitle class="text-wrap">{{
                        currentLicenseInfo.perpetual
                          ? $ay.t("LicenseTypePerpetual")
                          : $ay.t("LicenseTypeSubscription")
                      }}</v-list-item-subtitle>
                    </v-list-item-content>
                  </v-list-item>

                  <v-list-item
                    v-if="currentLicenseInfo.licenseWillExpire"
                    dense
                  >
                    <v-list-item-content>
                      <v-list-item-title>
                        {{ $ay.t("LicenseExpiration") }}</v-list-item-title
                      >
                      <v-list-item-subtitle class="text-wrap">{{
                        $ay.dt(currentLicenseInfo.licenseExpiration)
                      }}</v-list-item-subtitle>
                    </v-list-item-content>
                  </v-list-item>

                  <v-list-item dense>
                    <v-list-item-content
                      :class="{
                        'red--text text-h6':
                          currentLicenseInfo.maintenanceExpired
                      }"
                    >
                      <v-list-item-title>
                        {{ $ay.t("SupportedUntil") }}</v-list-item-title
                      >
                      <v-list-item-subtitle class="text-wrap">{{
                        $ay.dt(currentLicenseInfo.maintenanceExpiration)
                      }}</v-list-item-subtitle>
                    </v-list-item-content>
                  </v-list-item>

                  <v-subheader>{{ $ay.t("LicensedOptions") }}</v-subheader>

                  <v-list-item
                    v-for="item in currentLicenseInfo.features"
                    :key="item.Feature"
                    dense
                  >
                    <v-list-item-content>
                      <v-list-item-title>{{ item.Feature }}</v-list-item-title>
                      <v-list-item-subtitle class="text-wrap">{{
                        item.Count ? +item.Count : "&#10003;"
                      }}</v-list-item-subtitle>
                    </v-list-item-content>
                  </v-list-item>
                  <v-divider></v-divider>
                  <v-subheader>{{ $ay.t("Server") }}</v-subheader>
                  <v-list-item dense>
                    <v-list-item-content>
                      <v-list-item-title>{{
                        $ay.t("Version")
                      }}</v-list-item-title>
                      <v-list-item-subtitle class="text-wrap"
                        >{{ currentLicenseInfo.serverVersion }}&nbsp;{{
                          currentLicenseInfo.build
                        }}</v-list-item-subtitle
                      >
                    </v-list-item-content>
                  </v-list-item>

                  <v-list-item dense>
                    <v-list-item-content>
                      <v-list-item-title>{{
                        $ay.t("ActiveInternalUserCount")
                      }}</v-list-item-title>
                      <v-list-item-subtitle class="text-wrap">{{
                        currentLicenseInfo.activeInternalUserCount
                      }}</v-list-item-subtitle>
                    </v-list-item-content>
                  </v-list-item>
                  <v-list-item dense>
                    <v-list-item-content>
                      <v-list-item-title>{{
                        $ay.t("ActiveCustomerContactUserCount")
                      }}</v-list-item-title>
                      <v-list-item-subtitle class="text-wrap">{{
                        currentLicenseInfo.activeCustomerContactUserCount
                      }}</v-list-item-subtitle>
                    </v-list-item-content>
                  </v-list-item>
                </v-list>
              </v-card>
            </v-col>

            <v-col cols="12" md="7">
              <v-btn :href="purchaseLink()" target="_blank" class="mt-4 mr-4">{{
                $ay.t("PurchaseLicense")
              }}</v-btn>
              <v-btn class="mt-4" @click="fetchKey()">{{
                $ay.t("CheckForLicense")
              }}</v-btn>
            </v-col>
          </template>
          <template
            v-if="
              showLicenseUi() == 'needcantrial' ||
                showLicenseUi() == 'neednotrial'
            "
          >
            <!-- No license at all UI -->
            <v-col cols="12">
              <h2 class="mb-6 ml-1">{{ $ay.t("NoLicenseTitle") }}</h2>
              <v-expansion-panels focusable :value="0">
                <v-expansion-panel v-if="showLicenseUi() == 'needcantrial'">
                  <v-expansion-panel-header>{{
                    $ay.t("StartEvaluation")
                  }}</v-expansion-panel-header>
                  <v-expansion-panel-content>
                    <v-row dense>
                      <v-col cols="12">
                        <h4 class="mb-6 mt-3 ml-1">
                          {{ $ay.t("RequestEvaluationLicense") }}
                        </h4>
                      </v-col>
                      <v-col cols="12" sm="6" lg="4" xl="3">
                        <v-text-field
                          ref="requestcompany"
                          v-model="request.Company"
                          dense
                          :label="$ay.t('LicenseCompanyName')"
                          :rules="[form().required(this, 'requestcompany')]"
                          :error-messages="
                            form().serverErrors(this, 'requestcompany')
                          "
                          @input="fieldValueChanged('requestcompany')"
                        ></v-text-field>
                      </v-col>
                      <v-col cols="12" sm="6" lg="4" xl="3">
                        <v-text-field
                          ref="requestcontact"
                          v-model="request.Contact"
                          dense
                          :label="$ay.t('LicenseContactName')"
                          :rules="[form().required(this, 'requestcontact')]"
                          :error-messages="
                            form().serverErrors(this, 'requestcontact')
                          "
                          @input="fieldValueChanged('requestcontact')"
                        ></v-text-field>
                      </v-col>
                      <v-col cols="12" sm="6" lg="4" xl="3">
                        <v-text-field
                          ref="requestemail"
                          v-model="request.Email"
                          dense
                          :label="$ay.t('LicenseEmail')"
                          type="email"
                          :rules="[
                            form().required(this, 'requestemail'),
                            form().emailValid(this, 'requestemail')
                          ]"
                          :error-messages="
                            form().serverErrors(this, 'requestemail')
                          "
                          :hint="$ay.t('LicenseEmailVerficationHint')"
                          :persistent-hint="true"
                          @input="fieldValueChanged('requestemail')"
                        ></v-text-field>
                      </v-col>
                      <v-col cols="12">
                        <v-btn
                          :disabled="sendRequestDisabled()"
                          class="mt-4 mr-4"
                          @click="sendEvaluationRequest()"
                          >{{ $ay.t("SendEvaluationRequest") }}</v-btn
                        >

                        <v-btn class="mt-4" @click="fetchKey()">{{
                          $ay.t("CheckForLicense")
                        }}</v-btn>
                      </v-col>
                    </v-row>
                  </v-expansion-panel-content>
                </v-expansion-panel>
                <v-expansion-panel>
                  <v-expansion-panel-header>{{
                    $ay.t("PurchaseLicense")
                  }}</v-expansion-panel-header>
                  <v-expansion-panel-content>
                    <v-col cols="12">
                      <v-btn
                        :href="purchaseLink()"
                        target="_blank"
                        class="mt-4 mr-4"
                        >{{ $ay.t("PurchaseLicense") }}</v-btn
                      >
                      <v-btn class="mt-4" @click="fetchKey()">{{
                        $ay.t("CheckForLicense")
                      }}</v-btn>
                    </v-col>
                  </v-expansion-panel-content>
                </v-expansion-panel>
                <v-expansion-panel>
                  <v-expansion-panel-header>{{
                    $ay.t("HaveLicense")
                  }}</v-expansion-panel-header>
                  <v-expansion-panel-content>
                    <v-col cols="12">
                      <v-btn class="mt-4 mr-4" @click="helpRestore()">{{
                        $ay.t("HelpRestore")
                      }}</v-btn>
                      <!-- <v-btn class="mt-4 mr-4" @click="helpReleaseKey()">{{
                        $ay.t("HelpReleaseKey")
                      }}</v-btn> -->
                      <v-btn class="mt-4" @click="fetchKey()">{{
                        $ay.t("CheckForLicense")
                      }}</v-btn>
                    </v-col>
                  </v-expansion-panel-content>
                </v-expansion-panel>
              </v-expansion-panels>
            </v-col>
          </template>
        </v-row>
      </v-form>
    </v-col>
  </v-row>
</template>
<script>
const FORM_KEY = "adm-license";
const FORM_CUSTOM_TEMPLATE_KEY = null;
export default {
  components: {},
  data() {
    return {
      formCustomTemplateKey: FORM_CUSTOM_TEMPLATE_KEY,
      selectLists: {
        translations: []
      },
      licenseState: 0,
      dbIsEmpty: false,
      isRequesting: false,
      request: {
        Email: null,
        Company: "",
        Contact: null
      },
      currentLicenseInfo: {},
      formState: {
        ready: false,
        dirty: false,
        valid: true,
        readOnly: false,
        loading: true,
        errorBoxMessage: null,
        appError: null,
        serverError: {}
      },
      rights: window.$gz.role.getRights(window.$gz.type.License)
    };
  },
  computed: {
    canSave: function() {
      return this.formState.valid && this.formState.dirty;
    }
  },
  watch: {
    formState: {
      handler: function(val) {
        if (this.formState.loading) {
          return;
        }
        const canSave = val.dirty && val.valid && !val.readOnly;
        if (canSave) {
          window.$gz.eventBus.$emit("menu-enable-item", FORM_KEY + ":save");
        } else {
          window.$gz.eventBus.$emit("menu-disable-item", FORM_KEY + ":save");
        }
      },
      deep: true
    }
  },
  async created() {
    const vm = this;
    try {
      await initForm(vm);
      vm.rights = window.$gz.role.getRights(window.$gz.type.License);
      generateMenu(vm);
      vm.formState.loading = false;
      vm.formState.ready = true;
      window.$gz.eventBus.$on("menu-click", clickHandler);

      if (this.$store.state.l) {
        //license lockout, show popup and persistent error
        await window.$gz.dialog.displayLTModalNotificationMessage(
          "UserCountExceeded",
          null,
          "error",
          window.$gz.api.helpUrl() + "adm-license#user-count-exceeded"
        );
        //
      }

      this.$nextTick(() => {
        this.request.Company = null;
        this.fieldValueChanged(`requestcompany`);
      });
    } catch (err) {
      vm.formState.ready = true;
      window.$gz.errorHandler.handleFormError(err, vm);
    }
  },
  beforeDestroy() {
    window.$gz.eventBus.$off("menu-click", clickHandler);
  },
  methods: {
    purchaseLink() {
      return (
        "https://ayanova.com/r/pricing.htm?dbid=" +
        window.$gz.store.state.globalSettings.serverDbId
      );
    },
    helpRestore() {
      window.$gz.eventBus.$emit("menu-click", {
        key: "app:help",
        data: "ops-restore"
      });
    },
    helpReleaseKey() {
      window.$gz.eventBus.$emit("menu-click", {
        key: "app:help",
        data: "adm-license.md#key-release"
      });
    },
    showLicenseUi() {
      /*     public enum LicenseStatus
            {
                NONE = 0,
                ActiveTrial = 1,
                ExpiredTrial = 2,
                ActivePurchased = 3,
                ExpiredPurchased = 4,
                Revoked = 5
            } 
  */
      let licenseState = window.$gz.store.state.globalSettings.licenseStatus;
      //LICENSE STATUS: NONE, EXPIREDTRIAL
      if (licenseState == 0 || licenseState == 2) {
        return "needcantrial";
      }

      //LICENSE STATUS: EXPIREDPURCHASE
      if (licenseState == 4 || licenseState == 5) {
        return "neednotrial";
      }

      //LICENSE STATE: ActiveTrial or ActivePurchased
      if (licenseState == 1 || licenseState == 3) {
        return "ok";
      }
    },
    sendRequestDisabled() {
      //this is required because no rules are broken until entry starts so button is enabled
      if (this.request.Company == null) {
        return true;
      }
      if (this.isRequesting) {
        return true;
      }
      return !this.form().controlsAreAllValid(this, [
        "requestcompany",
        "requestcontact",
        "requestemail"
      ]);
    },
    async sendEvaluationRequest() {
      const vm = this;
      try {
        if (this.dbIsEmpty != true) {
          //We do not permit a re-request of a db with existing data so
          //the only solution is to erase the db or buy a license
          //Need to erase database
          let dialogResult = await window.$gz.dialog.confirmGeneric(
            "AdminEraseDatabaseWarning",
            "warning"
          );
          if (dialogResult == false) {
            return;
          }

          dialogResult = await window.$gz.dialog.confirmGeneric(
            "AdminEraseDatabaseLastWarning",
            "error"
          );
          if (dialogResult == false) {
            return;
          }
        }

        this.isRequesting = true;
        //call erase
        window.$gz.erasingDatabase = true; //suspend notify polling
        let r = await window.$gz.api.upsert(
          "license/permanently-erase-all-data-keep-tax-codes",
          "I understand"
        );
        window.$gz.erasingDatabase = false;

        //send request
        r = await window.$gz.api.upsert("license/trialRequest", vm.request);
        if (r.error) {
          throw new Error(window.$gz.errorHandler.errorToString(r, vm));
        }
        //a string is returned and will start with E1 if it's an error
        if (r.startsWith("E1")) {
          throw new Error(window.$gz.errorHandler.errorToString(r, vm));
        }

        if (r == "ok") {
          r = vm.$ay.t("EvaluationRequestReceived");
          window.$gz.eventBus.$emit("notify-success", r);
        } else {
          //some kind of non-ok issue but not an outright error
          window.$gz.eventBus.$emit("notify-info", r);
        }
        //then another message box saying watch your email to verify
      } catch (error) {
        window.$gz.errorHandler.handleFormError(error, vm);
      } finally {
        this.isRequesting = false;
      }
    },
    async fetchKey() {
      const vm = this;
      try {
        //check if we're still on the same "page" or the server has a different license
        //It might have been just installed by the server on it's own so check if we are not working with the most current license
        let currentServerLicenseInfo = await window.$gz.api.get("license");
        if (currentServerLicenseInfo.error) {
          throw new Error(
            window.$gz.errorHandler.errorToString(currentServerLicenseInfo, vm)
          );
        }
        currentServerLicenseInfo = currentServerLicenseInfo.data.license;

        if (
          currentServerLicenseInfo.keySerial != vm.currentLicenseInfo.keySerial
        ) {
          //the license has changed behind the scenes so act like it was a successful fetch
          await window.$gz.dialog.displayLTModalNotificationMessage(
            "NewLicenseInstalled"
          );
          vm.$router.push("/login");
          return;
        }
        //call fetch key on server
        let r = await window.$gz.api.upsert("license");
        //r should just be a string response unless there is an error in which case it's an object
        if (r.error) {
          throw new Error(window.$gz.errorHandler.errorToString(r, vm));
        }

        if (r.startsWith("E1")) {
          throw new Error(window.$gz.errorHandler.errorToString(r, vm));
        }
        //If here, there is no technical error
        //key might not exist or be not found but no error so r contains the deets
        if (r == "ok") {
          //all ok, new key installed time to logout and back in
          await window.$gz.dialog.displayLTModalNotificationMessage(
            "NewLicenseInstalled"
          );
          vm.$router.push("/login");
        } else {
          if (r == "notfound") {
            r = vm.$ay.t("NewLicenseNotFound");
          }
          window.$gz.eventBus.$emit("notify-info", r);
        }
      } catch (error) {
        window.$gz.errorHandler.handleFormError(error, vm);
      }
    },
    async erase() {
      const vm = this;

      try {
        if (this.dbIsEmpty != true) {
          let dialogResult = await window.$gz.dialog.confirmGeneric(
            "AdminEraseDatabaseWarning",
            "dire"
          );
          if (dialogResult == false) {
            return;
          }

          dialogResult = await window.$gz.dialog.confirmGeneric(
            "AdminEraseDatabaseLastWarning",
            "dire"
          );
          if (dialogResult == false) {
            return;
          }
        }
        //call erase
        window.$gz.erasingDatabase = true; //suspend notify polling
        await window.$gz.api.upsert(
          "license/permanently-erase-all-data-keep-tax-codes",
          "I understand"
        );

        vm.$router.push("/login");
      } catch (error) {
        window.$gz.errorHandler.handleFormError(error, vm);
      }
    },
    translation() {
      return window.$gz.translation;
    },

    form() {
      return window.$gz.form;
    },

    fieldValueChanged(ref) {
      if (!this.formState.loading && !this.formState.readOnly) {
        window.$gz.form.fieldValueChanged(this, ref);
      }
    }
  }
};

/////////////////////////////
//
//
function clickHandler(menuItem) {
  if (!menuItem) {
    return;
  }
  const m = window.$gz.menu.parseMenuItem(menuItem);
  if (m.owner == FORM_KEY && !m.disabled) {
    switch (m.key) {
      case "fetch":
        m.vm.fetchKey();
        break;
      case "erase":
        m.vm.erase();
        break;
      case "copydbid":
        window.$gz.util.copyToClipboard(
          window.$gz.store.state.globalSettings.serverDbId
        );
        break;
      case "eula":
        window.$gz.eventBus.$emit("menu-click", {
          key: "app:help",
          data: "license"
        });
        break;
      default:
        window.$gz.eventBus.$emit(
          "notify-warning",
          FORM_KEY + "::context click: [" + m.key + "]"
        );
    }
  }
}

//////////////////////
//
//
function generateMenu(vm) {
  const menuOptions = {
    isMain: true,
    icon: "$ayiTicket",
    title: "HelpLicense",
    helpUrl: "adm-license",
    formData: {
      ayaType: window.$gz.type.License
    },
    menuItems: []
  };

  //copy dbid
  menuOptions.menuItems.push({
    title: "CopyDbId",
    icon: "$ayiCopy",
    key: FORM_KEY + ":copydbid",
    vm: vm
  });

  if (vm.rights.change) {
    //Trigger license check
    menuOptions.menuItems.push({
      title: "CheckForLicense",
      icon: "$ayiTicket",
      key: FORM_KEY + ":fetch",
      vm: vm
    });

    //erase database
    if (window.$gz.store.getters.isSuperUser == true) {
      menuOptions.menuItems.push({
        title: "AdminEraseDatabase",
        icon: "$ayiSkullCrossbones",
        key: FORM_KEY + ":erase",
        vm: vm
      });
    }
  }
  menuOptions.menuItems.push({
    title: "ViewEULA",
    key: FORM_KEY + ":eula"
  });
  window.$gz.eventBus.$emit("menu-change", menuOptions);
}

/////////////////////////////////
//
//
async function initForm(vm) {
  await fetchTranslatedText(vm);
  let res = await window.$gz.api.get("license");
  if (!Object.prototype.hasOwnProperty.call(res, "data")) {
    return Promise.reject(res);
  }
  vm.currentLicenseInfo = res.data.license;

  res = await window.$gz.api.get("license/database-empty");
  if (!Object.prototype.hasOwnProperty.call(res, "data")) {
    return Promise.reject(res);
  }
  vm.dbIsEmpty = res.data;
}

//////////////////////////////////////////////////////////
//
// Ensures UI translated text is available
//
async function fetchTranslatedText() {
  await window.$gz.translation.cacheTranslations([
    "RegisteredUser",
    "DatabaseID",
    "LicenseSerial",
    "LicenseExpiration",
    "SupportedUntil",
    "LicensedOptions",
    "CheckForLicense",
    "SendEvaluationRequest",
    "NoLicenseTitle",
    "StartEvaluation",
    "PurchaseLicense",
    "HaveLicense",
    "LicenseCompanyName",
    "LicenseContactName",
    "LicenseEmail",
    "RequestEvaluationLicense",
    "LicenseEmailVerficationHint",
    "EvaluationRequestReceived",
    "AdminEraseDatabaseWarning",
    "AdminEraseDatabase",
    "AdminEraseDatabaseLastWarning",
    "NewLicenseInstalled",
    "NewLicenseNotFound",
    "HelpReleaseKey",
    "HelpRestore",
    "CopyDbId",
    "UserCountExceeded",
    "ViewEULA",
    "LicenseType",
    "LicenseTypeSubscription",
    "LicenseTypePerpetual",
    "Server",
    "Version",
    "ActiveCustomerContactUserCount",
    "ActiveInternalUserCount"
  ]);
}
</script>
