<template>
  <v-row v-if="formState.ready">
    <v-col>
      <v-form ref="form">
        <v-row>
          <gz-error :error-box-message="formState.errorBoxMessage"></gz-error>

          <v-col cols="12">
            <v-text-field
              name="username"
              id="username"
              v-model="obj.loginName"
              :readonly="formState.readOnly"
              prepend-icon="$ayiUser"
              autocomplete="off"
              autocorrect="off"
              autocapitalize="off"
              spellcheck="false"
              v-focus
              :label="$ay.t('UserLogin')"
              :rules="[form().required(this, 'loginName')]"
              :error-messages="form().serverErrors(this, 'loginName')"
              ref="loginName"
              @input="fieldValueChanged('loginName')"
              data-cy="loginName"
            ></v-text-field>
          </v-col>

          <v-col cols="12">
            <v-text-field
              name="password"
              id="password"
              v-model="obj.oldPassword"
              :readonly="formState.readOnly"
              :append-outer-icon="reveal ? '$ayiEye' : '$ayiEyeSlash'"
              prepend-icon="$ayiKey"
              :label="$ay.t('OldPassword')"
              :type="reveal ? 'text' : 'password'"
              :rules="[form().required(this, 'oldPassword')]"
              :error-messages="form().serverErrors(this, 'oldPassword')"
              ref="oldPassword"
              @input="fieldValueChanged('oldPassword')"
              @click:append-outer="reveal = !reveal"
            ></v-text-field>
          </v-col>

          <v-col cols="12">
            <v-text-field
              v-model="obj.newPassword"
              :readonly="formState.readOnly"
              :append-outer-icon="reveal ? '$ayiEye' : '$ayiEyeSlash'"
              prepend-icon="$ayiKey"
              :label="$ay.t('NewPassword')"
              :type="reveal ? 'text' : 'password'"
              :rules="[form().required(this, 'newPassword')]"
              :error-messages="form().serverErrors(this, 'newPassword')"
              ref="newPassword"
              @input="fieldValueChanged('newPassword')"
              @click:append-outer="reveal = !reveal"
            ></v-text-field>
          </v-col>

          <v-col cols="12">
            <v-text-field
              v-model="obj.confirmPassword"
              :readonly="formState.readOnly"
              :append-outer-icon="reveal ? '$ayiEye' : '$ayiEyeSlash'"
              prepend-icon="$ayiKey"
              :label="$ay.t('ConfirmPassword')"
              :type="reveal ? 'text' : 'password'"
              :rules="[
                form().required(this, 'confirmPassword'),
                form().confirmMatch(this, 'newPassword', 'confirmPassword')
              ]"
              :error-messages="form().serverErrors(this, 'confirmPassword')"
              ref="confirmPassword"
              @input="fieldValueChanged('confirmPassword')"
              @click:append-outer="reveal = !reveal"
            ></v-text-field>
          </v-col>
        </v-row>
      </v-form>
    </v-col>
  </v-row>
</template>

<script>
/////////////////////////////////////////////////////////////////////////////////////////////////////////////
/*  Xeslint-disable    */
////////////////////////////////////////////////////////////////////////////////////////////////////////////

const FORM_KEY = "home-password";
const API_BASE_URL = "auth/change-password";

export default {
  async created() {
    let vm = this;
    try {
      await initForm(vm);

      vm.rights = window.$gz.role.fullRightsObject();
      generateMenu(vm);
      vm.formState.ready = true;
      window.$gz.form.setFormState({
        vm: vm,
        dirty: false,
        valid: true,
        loading: false,
        readOnly: false
      });
      window.$gz.eventBus.$on("menu-click", clickHandler);
      //-------------
      //Set known password warning if applicable
      //note: all code assumes only one known user the superuser
      //if this changes then auth.js as well as store and here will need to be changed as well
      if (
        window.$gz.store.state.knownPassword &&
        (window.$gz.store.state.globalSettings.licenseStatus == 3 || //ActivePurchased = 3,
          window.$gz.store.state.globalSettings.licenseStatus == 4) // ExpiredPurchased = 4
      ) {
        this.formState.errorBoxMessage = vm.$ay.t("KnownPasswordWarning");
        this.obj.loginName = "superuser";
        this.obj.oldPassword = "l3tm3in";
      }
      //------------------
    } catch (err) {
      vm.formState.ready = true;
      window.$gz.errorHandler.handleFormError(err, vm);
    }
  },
  async beforeRouteLeave(to, from, next) {
    if (!this.formState.dirty) {
      next();
      return;
    }
    if ((await window.$gz.dialog.confirmLeaveUnsaved()) === true) {
      next();
    } else {
      next(false);
    }
  },
  beforeDestroy() {
    window.$gz.eventBus.$off("menu-click", clickHandler);
  },
  components: {},
  data() {
    return {
      obj: {
        loginName: null,
        oldPassword: null,
        newPassword: null,
        confirmPassword: null
      },
      reveal: true,
      formState: {
        ready: false,
        dirty: false,
        valid: true,
        readOnly: false,
        loading: true,
        errorBoxMessage: null,
        appError: null,
        serverError: {}
      },
      rights: window.$gz.role.fullRightsObject()
    };
  },
  //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: {
    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);
      }
    },
    async submit() {
      let vm = this;
      if (vm.canSave) {
        vm.formState.loading = true;

        //always submit from this form for the current logged in user id
        let url = API_BASE_URL;

        //clear any errors vm might be around from previous submit
        window.$gz.form.deleteAllErrorBoxErrors(vm);
        try {
          let res = await window.$gz.api.upsert(url, vm.obj);

          if (res.error) {
            vm.formState.serverError = res.error;
            window.$gz.form.setErrorBoxErrors(vm);
          } else {
            //Only a post, no data returned
            window.$gz.form.setFormState({
              vm: vm,
              dirty: false
            });
          }
        } catch (error) {
          window.$gz.errorHandler.handleFormError(error, vm);
        } finally {
          vm.loading = false;
        }
      }
    }
  }
};

/////////////////////////////
//
//
function clickHandler(menuItem) {
  if (!menuItem) {
    return;
  }
  let m = window.$gz.menu.parseMenuItem(menuItem);
  if (m.owner == FORM_KEY && !m.disabled) {
    switch (m.key) {
      case "save":
        m.vm.submit();
        break;

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

//////////////////////
//
//
function generateMenu(vm) {
  let menuOptions = {
    isMain: true,
    icon: "$ayiKey",
    title: "SetLoginPassword",
    helpUrl: "home-password",
    formData: {
      ayaType: window.$gz.type.UserOptions
    },
    menuItems: []
  };

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

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

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

//////////////////////////////////////////////////////////
//
// Ensures UI translated text is available
//
async function fetchTranslatedText(vm) {
  await window.$gz.translation.cacheTranslations([
    "UserLogin",
    "OldPassword",
    "NewPassword",
    "ConfirmPassword",
    "KnownPasswordWarning"
  ]);
}
</script>
