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

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

<script lang="ts">
import { defineComponent, useContext } from '@nuxtjs/composition-api'
import {useError} from "~/composables/form/useError";

export default defineComponent({
  props: {
    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
    }
  },
  setup (props, {emit}) {
    const { app: { i18n }, store } = useContext()
    const {violation, onChange} = useError(props.field, emit, store)

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

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

    return {
      label_field: props.label ?? props.field,
      rules,
      violation,
      onChange
    }
  }
})

function validEmail(email: string) {
  // regex from https://fr.vuejs.org/v2/cookbook/form-validation.html#Utiliser-une-validation-personnalisee
  const re = /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/
  return re.test(email)
}

</script>
