<template>
  <v-form ref="form">
    {{ formState }}
    <v-row v-if="formState.ready">
      <v-col cols="12">
        <v-text-field
          name="username"
          id="username"
          v-model="obj.loginName"
          :readonly="true"
          prepend-icon="$ayiUser"
          :label="$ay.t('UserLogin')"
          data-cy="loginName"
        ></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-col cols="12" mt-1 mb-5>
        <v-btn
          :disabled="!canSave"
          color="primary"
          value="SUBMIT"
          @click="submit()"
          data-cy="submit"
          >{{ $ay.t("Save") }}</v-btn
        >
      </v-col>
    </v-row>
  </v-form>
</template>

<script>
/*  Xeslint-disable */
export default {
  async created() {
    let searchParams = new URLSearchParams(window.location.search);
    //home-reset?rc={ResetCode}&tr={EffectiveTranslationId}&lg={loginName}
    this.obj.passwordResetCode = searchParams.get("rc");
    this.obj.loginName = searchParams.get("lg");
    this.obj.translationId = parseInt(searchParams.get("tr"));
    await initForm(this);
    this.formState.ready = true;
  },
  data() {
    return {
      obj: {
        newPassword: null,
        confirmPassword: null,
        passwordResetCode: null,
        loginName: null,
        translationId: 0 //1 //safety valve default to english
      },

      reveal: true,
      formState: {
        ready: false,
        dirty: false,
        valid: false,
        readOnly: false,
        loading: false,
        errorBoxMessage: null,
        appError: null,
        serverError: {}
      }
    };
  },
  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;

        let url = "auth/reset-password";

        try {
          let res = await window.$gz.api.upsert(url, {
            PasswordResetCode: vm.obj.passwordResetCode,
            Password: vm.obj.confirmPassword
          });

          if (res.error) {
            vm.formState.serverError = res.error;
            window.$gz.form.setErrorBoxErrors(vm);
          } else {
            vm.$router.push({
              name: "login",
              params: {
                presetLogin: vm.obj.loginName,
                presetPassword: vm.obj.confirmPassword
              }
            });
          }
        } catch (error) {
          window.$gz.errorHandler.handleFormError(error, vm);
        } finally {
          vm.loading = false;
        }
      }
    }
  }
};

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

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