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

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

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

          <v-col cols="12">
            <v-text-field
              ref="confirmPassword"
              v-model="obj.confirmPassword"
              dense
              :readonly="formState.readOnly"
              :append-outer-icon="reveal ? '$sockiEye' : '$sockiEyeSlash'"
              prepend-icon="$sockiKey"
              :label="$sock.t('ConfirmPassword')"
              :type="reveal ? 'text' : 'password'"
              :rules="[
                form().required(this, 'confirmPassword'),
                form().confirmMatch(this, 'newPassword', 'confirmPassword')
              ]"
              :error-messages="form().serverErrors(this, 'confirmPassword')"
              @input="fieldValueChanged('confirmPassword')"
              @click:append-outer="reveal = !reveal"
            ></v-text-field>
          </v-col>
        </v-row>
      </v-form>
    </v-col>
  </v-row>
</template>
<script>
const FORM_KEY = "home-password";
const API_BASE_URL = "auth/change-password";
export default {
  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()
    };
  },
  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.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);
    } 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);
  },
  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() {
      if (this.canSave) {
        this.formState.loading = true;
        window.$gz.form.deleteAllErrorBoxErrors(this);
        try {
          const res = await window.$gz.api.upsert(API_BASE_URL, this.obj);
          if (res.error) {
            this.formState.serverError = res.error;
            window.$gz.form.setErrorBoxErrors(this);
          } else {
            //Only a post, no data returned
            window.$gz.form.setFormState({
              vm: this,
              dirty: false
            });
          }
        } catch (error) {
          window.$gz.errorHandler.handleFormError(error, this);
        } finally {
          this.loading = false;
        }
      }
    }
  }
};

/////////////////////////////
//
//
function clickHandler(menuItem) {
  if (!menuItem) {
    return;
  }
  const 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) {
  const menuOptions = {
    isMain: true,
    icon: "$sockiKey",
    title: "SetLoginPassword",
    helpUrl: "home-password",
    formData: {
      sockType: window.$gz.type.UserOptions
    },
    menuItems: []
  };

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

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

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

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