<template>
  <div class="has-background-light fullheight" data-theme="light" lang="vi" v-if="authorized">
    <NuxtPage />
    <SnackBar @close="snackbar=undefined" v-bind="snackbar" v-if="snackbar" />
    <Modal @close="showmodal=undefined" v-bind="showmodal" v-if="showmodal" />
  </div>
</template>
<script setup>
  import SnackBar from '~/components/snackbar/SnackBar'
  import { onMounted } from 'vue'
  import { useStore } from '~/stores/index'
  import { useRoute } from 'vue-router'
  const route = useRoute()
  const store = useStore()
  const { $getdata, $requestLogin } = useNuxtApp()
  var snackbar = ref()
  var showmodal = ref()
  var authorized = ref()

  function getViewport() {
    let viewport
    var width = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth
    if(width<=768) viewport = 1 //'mobile'
    else if(width>=769 && width<=1023) viewport = 2  //'tablet'
    else if(width>=1024 && width<=1215) viewport = 3 //'desktop'
    else if(width>=1216 && width<=1407) viewport = 4 //'widescreen'
    else if(width>=1408) viewport = 5 //'fullhd'
    store.commit('viewport', viewport)
  }
  async function checkRedirect() {
    if(route.query.username && route.query.token) {
      let row = await $getdata('user', null, {filter: {username: route.query.username}, 
      values: 'id,avatar,username,fullname,type__code,type__name'}, true)
      if(row==='error' || row===undefined) $requestLogin()
      else {
        row.token = route.query.token
        store.commit('login', row)
      }
    } else if(!store.login) return $requestLogin()
    await checkLogin()
  }
  async function checkLogin() {
    if(store.login? store.login.token : false) {
      let authtoken = await $getdata('token', {token: store.login.token}, undefined, true)
      if(authtoken? authtoken.expiry : true) return $requestLogin()
      authorized.value = true
    } else $requestLogin()
  }
  onMounted(()=> {
    checkRedirect()
    getViewport()
  })
  watch(() => store.snackbar, (newVal, oldVal) => {
    snackbar.value = newVal
  })
  watch(() => store.showmodal, (newVal, oldVal) => {
    showmodal.value = newVal
  })
</script>