<!--
Champs de saisie de texte

@see https://vuetifyjs.com/en/components/text-fields/
-->

<template>
  <v-text-field
    autocomplete="off"
    :value="data"
    :label="$t(label_field)"
    :rules="rules"
    :disabled="readonly"
    :type="type === 'password' ? (show ? 'text' : type) : type"
    :error="error || !!violation"
    :error-messages="errorMessage || (violation ? $t(violation) : '')"
    @change="onChange($event); $emit('change', $event)"
    @input="$emit('input', $event, field)"
    v-mask="mask"
    :append-icon="type === 'password' ? (show ? 'mdi-eye' : 'mdi-eye-off') : ''"
    @click:append="show = !show"
  />
</template>

<script lang="ts">
import {defineComponent, ref, useContext} from '@nuxtjs/composition-api'
import {useError} from "~/composables/form/useError";
import {mask} from 'vue-the-mask';
import {Num} from "@vuex-orm/core";

export default defineComponent({
  props: {
    label: {
      type: String,
      required: false,
      default: null
    },
    field: {
      type: String,
      required: false,
      default: null
    },
    type: {
      type: String,
      required: false,
      default: null
    },
    data: {
      type: [String, Number],
      required: false,
      default: null
    },
    readonly: {
      type: Boolean,
      required: false
    },
    rules: {
      type: Array,
      required: false,
      default: () => []
    },
    error: {
      type: Boolean,
      required: false
    },
    errorMessage: {
      type: String,
      required: false,
      default: null
    },
    mask: {
      type: [Array, Boolean],
      required: false,
      default: false
    }
  },
  setup (props, {emit}) {
    const {store} = useContext()
    const {violation, onChange} = useError(props.field, emit, store)

    return {
      label_field: props.label ?? props.field,
      violation,
      show: ref(false),
      onChange
    }
  },
  directives: {
    mask: (el, binding, vnode, oldVnode) => {
      if (!binding.value) return;
      mask(el, binding, vnode, oldVnode);
    }
  }
})
</script>

<style scoped>
  input:read-only{
    color: #666 !important;
  }
</style>
