<template>
  <v-row v-if="formState.ready">
    <v-col>
      <v-form ref="form">
        <v-row>
          <gz-error :errorBoxMessage="formState.errorBoxMessage"></gz-error>
          <template v-if="showLicenseUi() == 'ok'"> normal license ui</template>
          <template v-if="showLicenseUi() == 'revoked'">
            Revoked license ui</template
          >
          <template
            v-if="
              showLicenseUi() == 'needcantrial' ||
                showLicenseUi() == 'neednotrial'
            "
          >
            <v-col cols="12">
              <h3 class="mb-6 ml-1">{{ $ay.t("NoLicenseTitle") }}</h3>
              <v-expansion-panels focusable>
                <v-expansion-panel v-if="showLicenseUi() == 'needcantrial'">
                  <v-expansion-panel-header>{{
                    $ay.t("StartEvaluation")
                  }}</v-expansion-panel-header>
                  <v-expansion-panel-content>
                    <!-- If status expiredtrial then they must erase before
                    requesting new license Erase database and request new trial
                    Erases db then goes to trial request form to trigger request
                    process If NONE then can just request license Goes to trial
                    request form to trigger request process -->
                    <v-row>
                      <v-col cols="12">
                        <h3 class="mb-6 mt-3 ml-1">
                          {{ $ay.t("RequestEvaluationLicense") }}
                        </h3>
                      </v-col>
                      <v-col cols="12" sm="6" lg="4" xl="3">
                        <v-text-field
                          v-model="request.Company"
                          :label="$ay.t('LicenseCompanyName')"
                          :rules="[form().required(this, 'requestcompany')]"
                          :error-messages="
                            form().serverErrors(this, 'requestcompany')
                          "
                          ref="requestcompany"
                          @input="fieldValueChanged('requestcompany')"
                        ></v-text-field>
                      </v-col>
                      <v-col cols="12" sm="6" lg="4" xl="3">
                        <v-text-field
                          v-model="request.Contact"
                          :label="$ay.t('LicenseContactName')"
                          :rules="[form().required(this, 'requestcontact')]"
                          :error-messages="
                            form().serverErrors(this, 'requestcontact')
                          "
                          ref="requestcontact"
                          @input="fieldValueChanged('requestcontact')"
                        ></v-text-field>
                      </v-col>
                      <v-col cols="12" sm="6" lg="4" xl="3">
                        <v-text-field
                          v-model="request.Email"
                          :label="$ay.t('LicenseEmail')"
                          type="email"
                          :rules="[
                            form().required(this, 'requestemail'),
                            form().emailValid(this, 'requestemail')
                          ]"
                          :error-messages="
                            form().serverErrors(this, 'requestemail')
                          "
                          ref="requestemail"
                          @input="fieldValueChanged('requestemail')"
                          :hint="$ay.t('LicenseEmailVerficationHint')"
                          :persistent-hint="true"
                        ></v-text-field>
                      </v-col>
                      <v-col cols="12">
                        <v-btn
                          :disabled="sendRequestDisabled()"
                          @click="sendRequest()"
                          >$ay.t('SendRequest')</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>
                    Takes to purchase page Purchase page has link to pricing and
                    help regarding licensing
                  </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>
                    Takes to manual / documentation page regarding this exact
                    issue If you have a backup Link to restore docs If you'd
                    like to start fresh contact to request license be freed up
                    again
                  </v-expansion-panel-content>
                </v-expansion-panel>
              </v-expansion-panels>
            </v-col>
          </template>
        </v-row>
      </v-form>
    </v-col>
  </v-row>
</template>
<script>
/////////////////////////////////////////////////////////////////////////////////////////////////////////////
/*  Xeslint-disable    */
////////////////////////////////////////////////////////////////////////////////////////////////////////////

const FORM_KEY = "adm-license";
const API_BASE_URL = null;
const FORM_CUSTOM_TEMPLATE_KEY = null;

export default {
  created() {
    let vm = this;
    initForm(vm)
      .then(() => {
        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);
      })
      .catch(err => {
        vm.formState.ready = true;
        window.$gz.errorHandler.handleFormError(err, vm);
      });
  },
  beforeRouteLeave(to, from, next) {
    if (this.formState.dirty) {
      window.$gz.dialog.confirmLeaveUnsaved().then(dialogResult => {
        if (dialogResult == true) {
          next();
        } else {
          next(false);
        }
      });
    } else {
      next();
    }
  },
  beforeDestroy() {
    window.$gz.eventBus.$off("menu-click", clickHandler);
  },
  components: {},
  data() {
    return {
      formCustomTemplateKey: FORM_CUSTOM_TEMPLATE_KEY,
      selectLists: {
        translations: []
      },
      licenseState: 0,
      request: {
        Email: "cardjohn@ayanova.com",
        Company: "Super TestCo",
        Contact: "Test Testerson"
      },
      obj: {},
      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)
    };
  },
  //WATCHERS
  watch: {
    formState: {
      handler: function(val) {
        //,oldval is available here too if necessary
        if (this.formState.loading) {
          return;
        }

        //enable / disable save button
        let 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
    }
  },
  computed: {
    canSave: function() {
      return this.formState.valid && this.formState.dirty;
    }
  },
  methods: {
    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) {
        return "neednotrial";
      }
      //LICENSE STATE: REVOKED
      if (licenseState == 5) {
        return "revoked";
      }

      //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;
      }
      return !this.form().controlsAreAllValid(this, [
        "requestcompany",
        "requestcontact",
        "requestemail"
      ]);
    },
    async sendRequest() {
      let vm = this;
      try {
        //Only no key or expired trial are here, not expired purchase
        //so safe to erase
        let dialogResult = await window.$gz.dialog.confirmGeneric(
          "AdminEraseDatabaseWarning"
        );
        if (dialogResult == false) {
          return;
        }
        //call erase
        let r = await window.$gz.api.upsertEx(
          "license/permanently-erase-all-data",
          "I understand"
        );

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

        window.$gz.eventBus.$emit("notify-success", r.data);

        //then another message box saying watch your email to verify
      } catch (error) {
        window.$gz.errorHandler.handleFormError(error, vm);
      }
    },
    async fetchKey() {
      let vm = this;
      try {
        //call fetch key on server
        let r = await window.$gz.api.upsertEx("license");
        if (r.error) {
          throw r;
        }
        window.$gz.eventBus.$emit("notify-info", r.data);
      } 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;
  }
  let m = window.$gz.menu.parseMenuItem(menuItem);
  if (m.owner == FORM_KEY && !m.disabled) {
    switch (m.key) {
      case "fetch":
        m.vm.fetchKey();
        break;

      default:
        window.$gz.eventBus.$emit(
          "notify-warning",
          FORM_KEY + "::context click: [" + m.key + "]"
        );
    }
  }
}

//////////////////////
//
//
function generateMenu(vm) {
  let menuOptions = {
    isMain: true,
    icon: "fa-ticket-alt",
    title: vm.$ay.t("HelpLicense"),
    helpUrl: "form-adm-license",
    formData: {
      ayaType: window.$gz.type.License
    },
    menuItems: []
  };

  if (vm.rights.change) {
    // menuOptions.menuItems.push({
    //   title: vm.$ay.t("Save"),
    //   icon: "fa-save",
    //   surface: true,
    //   key: FORM_KEY + ":save",
    //   vm: vm
    // });

    //Trigger license check
    menuOptions.menuItems.push({
      title: vm.$ay.t("CheckForLicense"),
      icon: "fa-ticket-alt",
      key: FORM_KEY + ":fetch",
      vm: vm
    });
  }

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

/////////////////////////////////
//
//
function initForm(vm) {
  return new Promise(async function(resolve, reject) {
    // (async function() {
    try {
      await fetchTranslatedText(vm);
      // await populateSelectionLists(vm);
    } catch (err) {
      reject(err);
    }
    resolve();
    // })();
  });
}

//////////////////////////////////////////////////////////
//
// Ensures UI translated text is available
//
function fetchTranslatedText(vm) {
  return window.$gz.translation.cacheTranslations([
    "CheckForLicense",
    "NoLicenseTitle",
    "StartEvaluation",
    "PurchaseLicense",
    "HaveLicense",
    "LicenseCompanyName",
    "LicenseContactName",
    "LicenseEmail",
    "RequestEvaluationLicense",
    "LicenseEmailVerficationHint",
    "AdminEraseDatabaseWarning" //preexisting
  ]);
}

// //////////////////////
// //
// //
// function populateSelectionLists(vm) {
//   //http://localhost:7575/api/v8/translation/list
//   return window.$gz.api.get("translation/list").then(res => {
//     if (res.error) {
//       window.$gz.errorHandler.handleFormError(res.error, vm);
//     } else {
//       vm.selectLists.translations = res.data;
//     }
//   });
// }
</script>
