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

<script>
export default {
  data() {
    return {
      obj: {
        newPassword: null,
        confirmPassword: null,
        passwordResetCode: null,
        loginName: null,
        translationId: 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;
    }
  },
  async created() {
    const 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;
  },
  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() {
      const vm = this;
      if (vm.canSave) {
        vm.formState.loading = true;
        try {
          const res = await window.$gz.api.upsert("auth/reset-password", {
            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",
      "ErrorAPI2000",
      "ErrorAPI2001",
      "ErrorAPI2004",
      "ErrorAPI2201",
      "ErrorAPI2203"
    ],
    vm.obj.translationId
  );
}
</script>
