<!--
An input for numeric values
-->

<template>
  <v-text-field
      ref="input"
      :modelValue.number="modelValue"
      :label="(label || field) ? $t(label ?? field) : undefined"
      hide-details
      :density="density"
      type="number"
      :variant="variant"
      @update:modelValue="modelValue = keepInRange(cast($event)); emitUpdate()"
  />
</template>

<script setup lang="ts">

import {PropType} from "@vue/runtime-core";

type Density = null | 'default' | 'comfortable' | 'compact';

const props = defineProps({
  modelValue: {
    type: Number
  },
  /**
   * Nom de la propriété d'une entité lorsque l'input concerne cette propriété
   * - Utilisé par la validation
   * - Laisser null si le champ ne s'applique pas à une entité
   */
  field: {
    type: String,
    required: false,
    default: null
  },
  /**
   * Label du champ
   * Si non défini, c'est le nom de propriété qui est utilisé
   */
  label: {
    type: String,
    required: false,
    default: null
  },
  default: {
    type: Number,
    required: false,
    default: 0
  },
  min: {
    type: Number,
    required: false,
    default: null
  },
  max: {
    type: Number,
    required: false,
    default: null
  },
  density: {
    type: String as PropType<Density>,
    required: false,
    default: 'default'
  },
  /**
   * @see https://vuetifyjs.com/en/api/v-autocomplete/#props-variant
   */
  variant: {
    type: String as PropType<"filled" | "outlined" | "plain" | "underlined" | "solo" | "solo-inverted" | "solo-filled" | undefined>,
    required: false,
    default: 'filled'
  }
})

/**
 * Reference to the v-text-field
 */
const input: Ref<any> = ref(null)

/**
 * Cast the value to a number, or fallback on default value
 * @param val
 */
const cast = (val: number | string): number => {
  val = Number(val)
  if (isNaN(val)) {
    return props.default
  }

  return val
}

/**
 * Ensure the value is between min and max values
 * @param val
 */
const keepInRange = (val: number) => {
  if (props.min !== null && props.max !== null && props.min >= props.max) {
    console.warn('Number input: minimum value is greater than maximum value')
  }
  if (props.min !== null && val < props.min) {
    val = props.min
  }
  if (props.max !== null && val > props.max) {
    val = props.max
  }
  return val
}


const emit = defineEmits(['update:modelValue'])

/**
 * Emit the update event
 */
const emitUpdate = () => {
  emit('update:modelValue', props.modelValue)
}

/**
 * Setup min and max values at the input level
 */
onMounted(() => {
  const inputElement = input.value.$el.querySelector('input')
  if (props.min !== null) {
    inputElement.min = props.min
  }
  if (props.max !== null) {
    inputElement.max = props.max
  }
})
</script>
