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

<template>
  <UiInputText
    :data="data"
    :label="label"
    :readonly="readonly"
    :error="error"
    :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: ''
    },
    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
    }
  },
  setup (props, {emit}) {
    const { app: { i18n }, store } = useContext()
    const {error, 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 {
      rules,
      error,
      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>
