<!--
Champs de saisie de type Text dédié à la saisie d'emails
-->

<template>
  <UiInputText
    :data="data"
    :label="$t(fieldLabel)"
    :readonly="readonly"
    :error="error || !!violation"
    :error-messages="errorMessage || violation ? $t(violation) : ''"
    :rules="rules"
    @update="onChange"
  />
</template>

<script setup lang="ts">

import {useNuxtApp} from "#app";
import {useFieldViolation} from "~/composables/form/useFieldViolation";
import {useValidationUtils} from "~/composables/utils/useValidationUtils";

const props = defineProps({
  label: {
    type: String,
    required: false,
    default: null
  },
  field: {
    type: String,
    required: false,
    default: null
  },
  data: {
    type: [String, Number],
    required: false,
    default: null
  },
  readonly: {
    type: Boolean,
    required: false,
    default: false
  },
  required: {
    type: Boolean,
    required: false,
    default: false
  },
  error: {
    type: Boolean,
    required: false
  },
  errorMessage: {
    type: String,
    required: false,
    default: null
  }
})

const { emit, i18n } = useNuxtApp()

const fieldLabel = props.label ?? props.field

const {violation, onChange} = useFieldViolation(props.field, emit)

const validationUtils = useValidationUtils()

const rules = [
  (email: string) => validationUtils.validEmail(email) || i18n.t('email_error')
]

if (props.required) {
  rules.push(
    (email: string) => !!email || i18n.t('required')
  )
}

</script>
