<template>
  <div>
    <vue-progress-bar></vue-progress-bar>
    <app-navbar></app-navbar>
    <section id="app" class="">
      <div class="container">
        <router-view v-if="!hasError"></router-view>
        <div v-else>
          <h1>Error!</h1>
          <p>{{error}}</p>
        </div>
      </div>
    </section>
  </div>
</template>

<script>

  import { mapMutations, mapState } from "vuex";
  import api from "../lib/Api";

  export default {
    data() {
      return {
        api: api
      };
    },
    computed: {
      ...mapState({
        hasError: state => state.error !== null,
        error: state => state.error,
        authChecked: state => state.authChecked
      })
    },

    methods: {
      ...mapMutations([
        'setUser'
      ])
    },

    watch: {
      isLoading(val) {
        if (val) {
          this.$Progress.start();
        } else {
          this.$Progress.finish();
        }
      }
    },

    created() {
      if (this.user === null && this.authChecked === false) {
        this.loadResource(api.getCurrentUser().then(user => this.setUser(user)));
      }

      // Hard coded values taken directly from Bulma css
      const mediaQueries = {
        mobile: "screen and (max-width: 768px)",
        tablet: "screen and (min-width: 769px)",
        tabletOnly: "screen and (min-width: 769px) and (max-width: 1023px)",
        touch: "screen and (max-width: 1023px)",
        desktop: "screen and (min-width: 1024px)",
        desktopOnly: "screen and (min-width: 1024px) and (max-width: 1215px)",
        widescreen: "screen and (min-width: 1216px)",
        widescreenOnly: "screen and (min-width: 1216px) and (max-width: 1407px)",
        fullhd: "screen and (min-width: 1408px)"
      };

      for (let device in mediaQueries) {
        const query = window.matchMedia(mediaQueries[device]);
        query.onchange = (q) => {
          this.$store.commit("setMediaQuery", {mediaName: device, value: q.matches});
        };
        query.onchange(query);
      }
    },

    components: {
    }
  }

</script>