<template>
  <v-container>
    <v-row>
      <v-col v-for="course, id in courses" :key="id">
        <v-card :width="vCardSize" :height="vCardSize" align="center" justify="center" @click="openCourse(id)">
          {{ id.toUpperCase() }} - {{ course.name }}
        </v-card>
      </v-col>
    </v-row>
  </v-container>
</template>

<script>
import _cloneDeep from 'lodash-es/cloneDeep'
import { collection, getDocs } from 'firebase/firestore'

export default {
  name: 'DashboardPage',
  layout ({ $auth }) {
    // Ref: https://firebase.google.com/docs/reference/js/v8/firebase.auth.Auth#currentuser
    return $auth.currentUser.emailVerified ? 'default' : 'unverified'
  },
  data () {
    return {
      vCardSize: 150
    }
  },
  computed: {
    courses () {
      return this.$store.state.courses
    }
  },
  created () {
    // Load all courses from the database and convert to JS object
    getDocs(collection(this.$db, 'kurse')).then(querySnapshot => {
      const courses = {}
      querySnapshot.forEach((doc) => {
        // doc.data() is never undefined for query doc snapshots
        courses[doc.id] = doc.data()
      })

      // Save courses in Vuex store
      this.$store.commit('setCourses', _cloneDeep(courses))
    })
  },
  methods: {
    openCourse (courseID) {
      this.$store.commit('setSelectedCourse', courseID)
      this.$router.push(`courses/${courseID}`)
    }
  }
}
</script>
