<template>
  <v-container>
    <Header />

    <template v-if="user">
      <p>user logged in: {{ user.login }}</p>

      <DeckList v-model="decks" />

      <v-btn @click.native="logout">Logout</v-btn>
    </template>
  </v-container>
</template>

<script>
import * as Cookies from 'js-cookie'
import axios from '@/plugins/axios'

import Header from '@/components/Header.vue'
import DeckList from '@/components/DeckList.vue'

export default {
  name: 'UserCP',

  components: {
    Header,
    DeckList
  },

  methods: {
    goHome() {
      Cookies.remove('session')
      this.$router.push({ name: 'home' })
    },

    logout() {
      axios
        .post('/user/logout', {
          session: Cookies.get('session')
        })
        .then(response => {
          if (response.data.success) {
            this.goHome()
          }
        })
    }
  },

  computed: {
    session: () => Cookies.get('session')
  },

  asyncComputed: {
    user() {
      return axios
        .post('/user/info', {
          session: this.session
        })
        .then(response => {
          if (response.data.success) {
            return response.data.user
          } else {
            this.goHome()
            return null
          }
        })
    },

    decks() {
      return axios
        .post('/decks/list', {
          session: this.session
        })
        .then(response => {
          if (response.data.success) {
            return response.data.decks
          }
        })
    }
  }
}
</script>
