<!--
Sélecteur de dates

@see https://vuetifyjs.com/en/components/date-pickers/
-->

<template>
  <main>
    <v-menu
      v-model="dateOpen"
      :close-on-content-click="false"
      :nudge-right="40"
      transition="scale-transition"
      offset-y
      min-width="auto"
    >
      <template v-slot:activator="{ on, attrs }">
        <v-text-field
          v-model="datesFormatted"
          autocomplete="off"
          :label="$t(label_field)"
          prepend-icon="mdi-calendar"
          :disabled="readOnly"
          v-bind="attrs"
          :dense="dense"
          :single-line="singleLine"
          v-on="on"
        />
      </template>
      <v-date-picker
        v-model="datesParsed"
        locale="fr"
        :range="range"
        color="ot_green lighten-1"
        @input="dateOpen = range && datesParsed.length < 2"
      />
    </v-menu>
  </main>
</template>

<script lang="ts">
import { defineComponent, watch, ref, useContext, onUnmounted, computed, Ref, ComputedRef } from '@nuxtjs/composition-api'
import { WatchStopHandle } from '@vue/composition-api'
import DatesUtils from '~/services/utils/datesUtils'

export default defineComponent({
  props: {
    field: {
      type: String,
      required: false
    },
    label: {
      type: String,
      required: false
    },
    data: {
      type: [String, Array],
      required: false
    },
    readOnly: {
      type: Boolean,
      required: false
    },
    range: {
      type: Boolean,
      required: false
    },
    dense: {
      type: Boolean,
      required: false
    },
    singleLine: {
      type: Boolean,
      required: false
    }
  },
  setup (props, { emit }) {
    const { data, field, range } = props
    const { $moment } = useContext()
    const dateUtils = new DatesUtils($moment)

    const datesParsed: Ref<Array<string>|string> = range ? ref(Array<string>()) : ref('')

    if (Array.isArray(datesParsed.value)) {
      for (const date of data as Array<string>) {
        if (date) { datesParsed.value.push($moment(date).format('YYYY-MM-DD')) }
      }
    } else {
      datesParsed.value = $moment(data as string).format('YYYY-MM-DD')
    }

    const datesFormatted: ComputedRef<string> = computed(() => {
      return dateUtils.formattedDate(datesParsed.value, 'DD/MM/YYYY')
    })

    const unwatch: WatchStopHandle = watch(datesParsed, (newValue, oldValue) => {
      if (newValue === oldValue) { return }
      if (Array.isArray(newValue) && newValue.length < 2) { return }
      emit('update', Array.isArray(newValue) ? dateUtils.sortDate(newValue) : newValue, field)
    })

    onUnmounted(() => {
      unwatch()
    })

    return {
      label_field: props.label ?? props.field,
      datesParsed,
      datesFormatted,
      dateOpen: ref(false)
    }
  }
})
</script>

<style scoped>
</style>
