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

<template>
  <UiInputText
    :data="data"
    :label="label"
    :readonly="readonly"
    :error="error"
    :error-message="errorMessage"
    :rules="rules"
    @change="$emit('update', $event, field)"
  />
</template>

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

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
    },
    error: {
      type: Boolean,
      required: false
    },
    errorMessage: {
      type: String,
      required: false,
      default: null
    }
  },
  setup (props) {
    const { app: { i18n } } = useContext()

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

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

    return {
      rules
    }
  }
})

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>
