<template>
  <v-row justify="center">
    <v-dialog persistent max-width="600px" :value="true">
      <v-card>
        <v-card-title>
          <span class="text-h5">Dodawanie miasta</span>
        </v-card-title>
        <v-card-text>
          <v-autocomplete
            v-model="select"
            :loading="loading"
            :items="items"
            item-value="id"
            item-text="name"
            :search-input.sync="search"
            cache-items
            class="mx-4"
            hide-no-data
            label="Wyszukaj miasto"
            solo-inverted
            clearable
          >
            <template slot="item" slot-scope="{ item }">
              <v-row align="center">
                <v-col cols="auto">
                  <v-img
                    width="32"
                    :src="
                      'https://www.countryflags.io/' +
                      item.country +
                      '/flat/32.png'
                    "
                  ></v-img>
                </v-col>
                <v-col>
                  {{ item.name }}
                </v-col>
              </v-row>
            </template>
            <template slot="selection" slot-scope="{ item }">
              <v-row align="center">
                <v-col cols="auto">
                  <v-img
                    width="32"
                    :src="
                      'https://www.countryflags.io/' +
                      item.country +
                      '/flat/32.png'
                    "
                  ></v-img>
                </v-col>
                <v-col cols="auto">
                  {{ item.name }}
                </v-col>
              </v-row>
            </template>
          </v-autocomplete>
        </v-card-text>
        <v-card-actions>
          <v-spacer></v-spacer>
          <v-btn color="blue darken-1" text @click="close()"> Zamknij </v-btn>
          <v-btn color="blue darken-1" text @click="save()" :disabled="!select"> Dodaj miasto </v-btn>
        </v-card-actions>
      </v-card>
    </v-dialog>
  </v-row>
</template>

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

@Component
export default class NewCity extends Vue {
  private close() {
    this.$emit("close");
  }

  private save() {
    this.$emit(
      "save",
      this.$data.items.find((el: any) => el.id === this.$data.select)
    );
    this.close();
  }

  @Watch("search")
  private queryCity() {
    if (this.$data.search.length > 0) {
      axios
        .get(process.env.VUE_APP_CITY_RESOLVER, {
          params: {
            query: this.$data.search,
          },
        })
        .then((res) => {
          console.log(res.data);
          this.$data.items = res.data;
        });
    }
  }

  private data() {
    return {
      loading: false,
      items: [],
      search: null,
      select: null,
    };
  }
}
</script>