import Vue from 'vue'
import Axios from 'axios'
import router from './router'
import Vuetify from 'vuetify'
import { store } from './store'
import 'vuetify/dist/vuetify.css'
import App from './App.vue'
import VueRouter from 'vue-router'
import localAuth from './localAuth'
import 'mdi/scss/materialdesignicons.scss'
import { mapActions, mapState } from 'vuex'
import VueSweetalert2 from 'vue-sweetalert2'
import sk from 'vee-validate/dist/locale/sk'
import VeeValidate, { Validator } from 'vee-validate'

Validator.localize('sk', sk)

Vue.use(Vuetify, {
  iconfont: 'mdi',
  theme: {
    primary: '#4caf50',
    secondary: '#4caf50',
    tertiary: '#495057',
    accent: '#82B1FF',
    error: '#f55a4e',
    info: '#00d3ee',
    success: '#5cb860',
    warning: '#ffa21a'
  }
})
Vue.use(VueRouter)
Vue.use(VeeValidate)
Vue.use(VueSweetalert2)

new Vue({
  el: '#app',
  store,
  router,
  render: h => h(App),
  mounted () {
    this.$store.subscribe((mutation, state) => {
      if (String(mutation.type).endsWith('_FAILED')) {
        if (mutation.payload.response.status === 401) {
          router.push({name: 'Prihlásenie'})
        }
      }
    })
  },
  created () {
    if (!localAuth.jePouzivatelAutentifikovany()) {
      router.push({name: 'Prihlásenie'})
    } else {
      Axios.defaults.headers.common['Authorization'] = 'Bearer ' + localAuth.apiToken()
      this.ziskajUdajeOAutentifikovanomPouzivatelovi()
        .then(() => {
          router.push({
            name: 'Knižnica'
          })
        })
    }
  },
  methods: {
    ...mapActions('pouzivatelia', [
      'ziskajUdajeOAutentifikovanomPouzivatelovi'
    ])
  }
})
