<template>
  <div id="app">
    <template v-if="user.authenticated">
      <div class="ui secondary menu">
        <router-link to="/" class="item" v-lang.nav.home></router-link>
        <router-link to="/books" class="item" v-lang.nav.books></router-link>
        <router-link to="/authors" class="item" v-lang.nav.authors></router-link>
        <router-link to="/publishers" class="item" v-lang.nav.publishers></router-link>
        <div class="right menu">
          <img v-bind:src="gravatar" class="menu-avatar"/>
          <div class="ui item"> {{ user.infos.username }}</div>
          <a class="ui item" @click="logout()">
            <icon name="sign-out"></icon>
          </a>
        </div>
      </div>
    <div class="ui divider"></div>
    </template>
    <router-view/>
    <button @click="language = 'en'">EN</button>
    <button @click="language = 'de'">DE</button>
    <button @click="language = 'fr'">FR</button>
    <notifications position="bottom left" />
  </div>
</template>

<script>
import auth from './auth'
import router from './router'

export default {
  name: 'app',
  data () {
    return {
      user: auth.user,
      gravatar: ''
    }
  },
  created () {
    // Redirect the user to the login page if he's not logged in
    if (!this.user.authenticated) {
      this.logout()
      router.push({ name: 'login' })
    }

    // Set the users avatar
    this.setAvatar()
  },
  watch: {
    // call again the method if the route changes
    '$route': 'setAvatar'
  },
  methods: {
    logout () {
      auth.logout()
    },
    setAvatar () {
      auth.getUserInfos()
      this.gravatar = 'https://www.gravatar.com/avatar/' + this.user.infos.avatar + '?s=40&d=mm'
    }
  }
}
</script>

<style>
  *, *:hover, *:active, *:focus{
    outline: none;
  }

  #app{
    margin: 0 1em;
    padding-top: 1.5em;
  }

  .menu-avatar{
    -webkit-border-radius: 3px;
    -moz-border-radius: 3px;
    border-radius: 3px;
  }
</style>
