<template>
    <n-form
        :model="userModel"
        label-placement="left"
        require-mark-placement="right-hanging"
        label-width="auto"
    >
        <n-form-item label="Benutzername" path="username">
            <n-input 
                v-model:value="userModel.username"
            />
        </n-form-item>

        <n-form-item label="Ist Admin?" path="is_admin">
            <n-checkbox v-model:checked="userModel.is_admin" />
        </n-form-item>

        <n-form-item label="Passwort" path="password">
            <n-input 
                type="password"
                show-password-on="mouseclick"
                placeholder="Passwort"
                v-model:value="userModel.password"
            />
        </n-form-item>

        <n-form-item>
            <n-input 
                type="password"
                show-password-on="mouseclick"
                placeholder="Passwort wiederholen"
                v-model:value="userModel.password_repeat"
            />
        </n-form-item>
    </n-form>
</template>

<script setup>

const props = defineProps({
    userModel: Object
})

const rules = {
    username: [{
        required: true,
        message: "Benutzername ist erforderlich",
    }],
    password: [{
        required: true,
        message: "Passwort ist erforderlich",
    }],
    password_repeat: [{
        required: true,
        message: "Wiederholtes Passwort ist erforderlich",
        trigger: ["input", "blur"],
    },{
        validator: validatePassword,
        message: "Passwörter stimmen nicht überein",
        trigger: "input",
    },{
        validator: validatePassword,
        message: "Passwörter stimmen nicht überein",
        trigger: ["blur", "password-input"],
    }]
}

function validatePassword(rule, value) {
    return (!!userModel.password 
        && userModel.password.startsWith(value) 
        && userModel.password.lenght >= value.length) 
        || (userModel.password === value)
}
</script>