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

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

        <DeckList />
      </template>
    </v-container>
  </v-content>
</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
  },

  data: () => ({}),

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

    logout() {
      axios
        .post('/user/logout', {
          session: this.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
          }
        })
    }
  }
}
</script>
