<script setup>
import { useI18n } from "vue-i18n";
import { Dialog } from "quasar";
import { reset } from "@formkit/core";
import { computed } from "vue";
import { q } from "#imports";
import { updatePassword } from "@hostlink/light";
const { t } = useI18n();
const onSubmit = async (data, form) => {
  if (await updatePassword(data.old_password, data.new_password)) {
    reset(form);
    await Dialog.create({
      title: "Password updated",
      message: "Your password has been updated",
      ok: "OK"
    });
  } else {
    await Dialog.create({
      title: "Error",
      message: "Old password is incorrect",
      ok: "OK"
    });
  }
};
const { system } = await q({
  system: { passwordPolicy: true }
});
const policies = computed(() => {
  return system.passwordPolicy.split("|").map((policy) => {
    let name = policy.split(":")[0];
    if (name == "length") {
      return t("Must contain at least {0} characters", [policy.split(":")[1]]);
    }
    return t(name);
  });
});
</script>

<template>
    <FormKit type="l-form" :bordered="false" @submit="onSubmit">
        <FormKit type="l-input" label="Old password" name="old_password" inputType="password" validation="required"
            autocomplete="current-password" />
        <FormKit type="l-input" label="New password" name="new_password" inputType="password"
            :validation="system.passwordPolicy" autocomplete="new-password" />
        <FormKit type="l-input" label="Confirm password" name="new_password_confirm" inputType="password"
            validation="required|confirm" />
    </FormKit>

    <q-separator spaced />

    <q-card flat :bordered="false">
        <q-card-section>
            <div>{{ $t('Password policy') }}</div>
            <ul>
                <li v-for="policy in policies" :key="policy">{{ policy }}</li>
            </ul>
        </q-card-section>
    </q-card>
</template>
