<template>
  <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="dateFormatted"
        :label="$t(label_field)"
        prepend-icon="mdi-calendar"
        :disabled="readOnly"
        v-bind="attrs"
        v-on="on"
      ></v-text-field>
    </template>
    <v-date-picker
      v-model="dateParsed"
      @input="dateOpen = false"
      locale="fr"
      color="ot_green lighten-1"
    ></v-date-picker>
  </v-menu>
</template>


<script lang="ts">
  import {defineComponent, watch, ref, useContext, onUnmounted, computed, toRef} from '@nuxtjs/composition-api'
  import {useRepositoryHelper} from "~/use/store/useRepository";
  import {Repository} from "@vuex-orm/core";
  import {Model} from "~/models/Model";

  export default defineComponent({
    props: {
      repository: {
        type: Object as () => Repository<Model>,
        required: true
      },
      entry:{
        type: Object,
        required: true
      },
      field: {
        type: String,
        required: true
      },
      label: {
        type: String,
        required: false
      }
    },
    setup(props){
      const {label, field, repository } = props
      const entry = toRef(props, 'entry')

      const {$moment} = useContext()
      const label_field = label ?? field;

      const data = computed(() => entry.value[field])
      const readOnly = computed(() => useRepositoryHelper.getReadOnly(repository))

      const dateFormatted = ref($moment(data.value).format('DD/MM/YYYY'))
      const dateParsed = ref($moment(data.value).format('YYYY-MM-DD'))

      const unwatch = watch(dateParsed, (newValue) => {
        dateFormatted.value = $moment(newValue).format('DD/MM/YYYY')
        useRepositoryHelper.updateStoreFromField(repository, entry.value, newValue, field)
      })

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

      return {
        label_field,
        readOnly,
        dateParsed,
        dateFormatted,
        dateOpen: false
      }
    }
  })
</script>

<style scoped>
</style>
