<template>
  <li class="dropdown user user-menu">
    <a href="javascript:;" class="dropdown-toggle" data-toggle="dropdown">
      <!-- The user image in the navbar-->
      <img :src="user.avatar" class="user-image" alt="User Image">
      <!-- hidden-xs hides the username on small devices so only the image appears. -->
      <span class="hidden-xs">{{userData.email}}</span>
    </a>
    <!-- Account Info and Menu -->
    <ul class="dropdown-menu">
      <li class="user-header" style="height:auto;min-height:85px;padding-bottom:15px;">
        <p>
          <span>{{userData.email}}</span>
          <small v-for="role in user.roles" :key="role">{{role}}</small>
        </p>
      </li>
      <li class="user-footer">
      <!-- <router-link tag="li" class="pageLink" to="/login"> -->
        <a href="javascript:;" @click="logout" class="btn btn-default btn-flat btn-block">
          <i class="fa fa-sign-out"></i>
          <span>Logout</span>
        </a>
        <!-- </router-link> -->
      </li>
    </ul>
  </li>
</template>

<script>

import api from '../../api'
import config from '../../config'

export default {
  name: 'UserMenu',
  props: ['user'],
  methods: {
    logout() {
      this.access_token = localStorage.getItem('token')
      var params = {'client_id': config.clientId, 'client_secret': config.clientSecret, 'access_token': this.access_token}
      api
        .request('post', 'logout', params)
        .then(response => {
          this.toggleLoading()
          var data = response.data
          if (data.status === 'success') {
            localStorage.removeItem('user')
            localStorage.removeItem('token')
            this.$router.push('/')
          }
        })
        .catch(error => {
          console.log(error)
          this.$store.commit('TOGGLE_LOADING')
          this.response = 'Server appears to be offline'
        })
    },
    toggleLoading() {
      this.loading = this.loading === '' ? 'loading' : ''
    }
  },
  created: function() {
    this.userData = JSON.parse(localStorage.getItem('user'))
  }
}
</script>