<template>
  <ui-input
    @input="onInput"
    :value="dimensions"
    label="Габариты Д×Ш×В"
    name="dimensions"
    placeholder="100 100 100"
  />
</template>

<script lang="ts">
import { Component, Vue, Watch } from 'vue-property-decorator'
import UiInput from '../../../form/UiInput.vue'
import DeliveryCalculatorStore, {
  getDeliveryCalculatorStore,
} from '../utils/DeliveryCalculatorStore'
import { Dimensions } from '../dto/Dimensions'

@Component({
  components: { UiInput },
})
export default class DimensionsField extends Vue {
  dimensions = ''

  calculatorStore!: DeliveryCalculatorStore

  created() {
    this.calculatorStore = getDeliveryCalculatorStore(this.$store)
  }

  onInput(value: string) {
    const values = (value.match(/\d+(\.\d+)?/g) || []).slice(0, 3)
    this.dimensions = values.join(' ')
  }

  @Watch('dimensions')
  setSizes(value: string) {
    const dimensionsAsArray = value.split(' ').map(size => parseInt(size) || 0)

    this.calculatorStore.setDimensions(dimensionsAsArray as Dimensions)
  }
}
</script>
