<template>
  <ui-autocomplete
    v-bind="$attrs"
    v-on="$listeners"
    @filter="filterCountries"
    v-model="country"
    :options="countries"
    :option-label="option => option.name"
    :option-value="option => option"
    label="Куда страна"
    name="destination.country"
  />
</template>

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

@Component({
  components: { UiAutocomplete },
  inheritAttrs: false,
})
export default class ToCountrySelect extends Vue {
  countries: Country[] = []
  calculatorStore!: DeliveryCalculatorStore

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

  get country(): Country | null {
    return this.calculatorStore.country
  }

  set country(country: Country | null) {
    if (country) {
      this.calculatorStore.setCountry(country)
    }
  }

  filterCountries(query: string, update: Function) {
    LocationService.getCountries()
      .then(countries =>
        countries.filter(country =>
          country.name.toLowerCase().includes(query.toLowerCase())
        )
      )
      .then(countries => update(() => (this.countries = countries)))
  }
}
</script>
