<template>
  <Header v-if="user">
    <v-btn flat :to="{ name: 'deckcp' }">
      <v-icon>view_carousel</v-icon> Decks
    </v-btn>

    <v-btn flat> <v-icon>play_arrow</v-icon> Play </v-btn>

    <v-btn flat :to="{ name: 'usercp' }">
      <v-icon>person</v-icon> {{ user.login }}
    </v-btn>

    <v-dialog v-model="logging_out">
      <template v-slot:activator="{ on }">
        <v-btn flat v-on="on"> <v-icon>power_off</v-icon> Logout </v-btn>
      </template>

      <v-card>
        <v-card-title class="headline">
          Log Out?
        </v-card-title>

        <v-card-text>
          Are you sure you want to log out?
        </v-card-text>

        <v-card-actions>
          <v-spacer></v-spacer>

          <v-btn color="error" @click.native="logging_out = false">
            Cancel
          </v-btn>

          <v-btn color="success" @click.native="logout">
            Confirm
          </v-btn>
        </v-card-actions>
      </v-card>
    </v-dialog>
  </Header>
</template>

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

import Header from './Header'

export default {
  name: 'HeaderIntern',

  components: {
    Header
  },

  data: () => ({
    logging_out: false
  }),

  props: {
    value: String
  },

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

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

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

  asyncComputed: {
    user: {
      get() {
        return axios
          .post('/user/info', {
            session: this.session
          })
          .then(response => {
            if (response.data.success) {
              this.$emit('input', this.session)
              this.$emit('user', response.data.user)
              return response.data.user
            } else {
              this.goHome()
              return null
            }
          })
      },
      default: {
        user: 0,
        login: '',
        settings: ''
      }
    }
  }
}
</script>
