<template>
  <div>
    <v-card flat tile>
      <v-card-title>Prognoza pogody</v-card-title>
      <v-row justify="space-around">
        <v-col v-for="(city, i) in cities" :key="i">
          <City :city="city" @delete="deleteCity(city)" />
        </v-col>
        <v-col>
          <v-hover v-slot="{ hover }">
            <v-card
              tile
              outlined
              height="283"
              width="350"
              :color="hover ? 'grey lighten-2' : ''"
              class="rounded-xl"
              style="outline-style: dashed"
              :style="hover ? 'cursor: pointer;' : ''"
              @click="add = true"
            >
              <v-row align="center" justify="center" class="fill-height">
                <v-col cols="auto" class="px-0">
                  <v-icon size="60" left>mdi-plus</v-icon>
                </v-col>
                <v-col cols="auto" class="px-0">
                  <span class="text-h4">Dodaj miasto</span>
                </v-col>
              </v-row>
            </v-card>
          </v-hover>
        </v-col>
      </v-row>
    </v-card>
    <NewCity v-if="add" @save="addCity($event)" @close="add = false" />
  </div>
</template>

<script lang="ts">
import { Component, Vue } from "vue-property-decorator";
import City from "@/components/City.vue";
import NewCity from "@/components/NewCity.vue";
import { nanoid } from "nanoid";
import {
  collection,
  query,
  doc,
  where,
  getDocs,
  setDoc,
  getFirestore,
} from "firebase/firestore";

@Component({
  components: {
    City,
    NewCity,
  },
})
export default class Forecast extends Vue {
  private db = getFirestore();
  private users = collection(this.db, "users");

  private created() {
    this.getFirebaseUserData();
  }

  private addCity(city: object) {
    this.$data.cities.push(city);
    this.saveUser();
  }

  deleteCity(city: object) {
    this.$data.cities.splice(this.$data.cities.indexOf(city));
    this.saveUser();
  }

  private async getFirebaseUserData() {
    const q = query(this.users, where("uid", "==", this.user.uid));

    const querySnapshot = await getDocs(q);

    if (querySnapshot.size > 0) {
      this.$data.dataID = querySnapshot.docs[0].id;
      this.$data.cities = querySnapshot.docs[0].data().cities;
    } else {
      this.saveUser(nanoid());
    }
  }

  private async saveUser(id: string = this.$data.dataID) {
    if (this.$data.dataID === undefined) {
      this.$data.dataID = id;
    }
    await setDoc(doc(this.users, id), {
      uid: this.user.uid,
      cities: this.$data.cities,
    });
  }

  get user() {
    return this.$store.getters.user;
  }

  private data() {
    return {
      cities: [],
      add: false,
    };
  }
}
</script>