<template>
  <div>
    <v-autocomplete
      v-model="model"
      :loading="loading"
      :items="items"
      :search-input.sync="search"
      hide-no-data
      hide-details
      return-object
      auto-select-first
      clearable
      :label="$t('where') + ' ?'"
      outlined
      append-icon="mdi-crosshairs-gps"
      @change="$emit('change', $event ? $event.value : '')"
      @click:append="geolocalizeUser"
    />
    <v-snackbar :value="errorMsg !== ''">
      {{ errorMsg }}
      <template #action="{ attrs }">
        <v-btn text v-bind="attrs" @click="errorMsg=''">
          {{ $t('close') }}
        </v-btn>
      </template>
    </v-snackbar>
  </div>
</template>

<script>
export default {
  props: {
    value: {
      type: String,
      required: false,
      default: ''
    },
    type: {
      type: String,
      required: false,
      default: 'housenumber',
      validator (value) {
        return ['housenumber', 'street', 'locality', 'municipality'].includes(value)
      }
    },
    limit: {
      type: Number,
      required: false,
      default: 5
    },
    autocomplete: {
      type: Boolean,
      required: false,
      default: true
    }
  },
  data () {
    return {
      model: null,
      search: null,
      features: [],
      loading: false,
      errorMsg: ''
    }
  },
  computed: {
    items () {
      return this.features.map((f) => {
        return {
          text: f.properties.name + ' (' + f.properties.postcode + ')',
          value: { longitude: f.geometry.coordinates[0], latitude: f.geometry.coordinates[1] },
          disabled: false
        }
      })
    }
  },
  watch: {
    search (val) {
      if (!val) {
        this.features = []
        return
      }

      this.loading = true

      // Lazily load input items
      const apiUrl = 'https://api-adresse.data.gouv.fr/search/' +
                     `?type=${this.type}` +
                     `&autocomplete=${this.autocomplete ? 1 : 0}` +
                     `&limit=${this.limit}` +
                     `&q=${val}`
      fetch(encodeURI(apiUrl))
        .then(res => res.json())
        .then(({ features }) => {
          this.features = features
        })
        .catch((err) => {
          // eslint-disable-next-line no-console
          console.error(err)
        })
        .finally(() => {
          this.loading = false
        })
    }
  },
  methods: {
    clear () {
      this.model = null
      this.search = null
      this.features = []
      this.loading = false
      this.errorMsg = ''
    },
    geolocalizeUser () {
      if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(
          (position) => {
            this.latitude = position.coords.latitude
            this.longitude = position.coords.longitude
            this.text = this.$t('my_position')
          },
          () => {
            this.errorMsg = this.$t('geolocation_error')
          }
        )
      } else {
        this.errorMsg = this.$t('geolocation_not_supported')
      }
    }
  }
}
</script>

<style>
.v-input__control {
  height: 56px;
}
</style>
