<template>
  <base-input
    :value="fValue"
    :data-testid="testId"
    :disabled="disabled"
    :error="error"
    :input-id="inputId"
    @input="onInput"
    @blur="emitInput" />
</template>

<script lang="ts">
import { Vue, Component, Prop, Watch } from 'vue-property-decorator'

import { formatInputDate, parseInputDate } from '../../core/time/TimeUtils'

import InputEvent from '../../core/events/InputEvent'

import BaseInput from './BaseInput.vue'

@Component({
  name: 'base-date-input',
  components: {
    BaseInput
  }
})
export default class BaseDateInput extends Vue {
  @Prop() value!: Date | null
  @Prop() readonly inputId!: string
  @Prop() readonly testId!: string
  @Prop({ default: false }) disabled!: boolean
  @Prop({ default: false }) error!: boolean

  fValue = ''

  @Watch('value', { immediate: true })
  onValueChange (value: Date | null) {
    if (value === undefined) {
      console.warn('base-date-input undefined value')
      this.fValue = ''
    } else if (value !== null) {
      this.fValue = formatInputDate(value, 'it-IT')
    } else {
      this.fValue = ''
    }
  }

  onInput ($event: InputEvent<string>) {
    this.fValue = $event.value!
  }

  emitInput () {
    const value = parseInputDate(this.fValue, 'it-IT')
    if (value !== null) {
      this.fValue = formatInputDate(value, 'it-IT')
    } else {
      this.fValue = ''
    }
    const event = new InputEvent<Date>()
    event.value = value
    this.$emit('input', event)
  }
}
</script>

<style lang="scss" scoped>
@import "../../core/base/bulma.scss";
@import "bulma/sass/form/shared.sass";
@import "bulma/sass/form/input-textarea.sass";
</style>
