<template>
  <v-app id="app">
    <AppBar />
    <Drawer />
    <StaticFab />

    <v-main dark app class="grey darken-4">
      <router-view />
    </v-main>
  </v-app>
</template>

<script>
import AppBar from "@/components/AppBar.vue";
import Drawer from "@/components/Drawer.vue";
import StaticFab from "@/components/StaticFab.vue";
import { API } from "./utils/api_common";
import jwt_decode from "jwt-decode";

export default {
  name: "App",
  components: {
    AppBar,
    Drawer,
    StaticFab,
  },

  data: () => ({
    timer: null,
  }),
  mounted() {
    if (
      localStorage.getItem("token") &&
      jwt_decode(localStorage.getItem("token")).exp < Date.now() / 1000
    ) {
      localStorage.removeItem("token");
      this.$router.push({ name: "Login" });
    }
    this.$store.dispatch("loadCurrentUser");
    this.timer = setInterval(this.refreshUser.bind(this), 10000);
  },
  methods: {
    refreshUser() {
      let token = localStorage.getItem("token");
      if (
        token &&
        jwt_decode(token).exp >= Date.now() / 1000 &&
        jwt_decode(token).exp - Date.now() / 1000 < 120
      ) {
        API
          .get("api/v1/users/refresh", {
            headers: { Authorization: localStorage.getItem("token") },
          })
          .then((response) => {
            if (response.status == 200 && response.data.token) {
              localStorage.setItem("token", response.data.token);
              this.$store.dispatch("loadCurrentUser");
            }
          });
      } else if (token && jwt_decode(token).exp < Date.now() / 1000) {
        localStorage.removeItem("token");
        this.$router.push({ name: "Login" });
      } else {
        this.$store.dispatch("loadCurrentUser");
      }
    },
    cancelAutoUpdate() {
      clearInterval(this.timer);
    },
  },
  beforeDestroy() {
    this.cancelAutoUpdate();
  },
};
</script>
