import Vue from 'vue'
import Vuex from 'vuex'

import api from '../lib/Api';

Vue.use(Vuex);

export default new Vuex.Store({
  strict: process.env.NODE_ENV !== 'production',
  state: {
    updateAvailable: false,
    loadingCount: 0,
    loading: false,
    error: null,
    authChecked: false,
    user: null,

    // MediaQueryList objects in the root App component maintain this state.
    mediaQueries: {
      mobile: false,
      tablet: false,
      tabletOnly: false,
      touch: false,
      desktop: false,
      desktopOnly: false,
      widescreen: false,
      widescreenOnly: false,
      fullhd: false
    }
  },
  getters: {
    isLoading(state) {
      return state.loading === true;
    },
    isLoggedIn(state) {
      return state.user !== null;
    },
    isAdmin(state) {
      return state.user !== null && state.user.admin === true;
    }
  },
  mutations: {
    setUpdateAvailable(state, value) {
      state.updateAvailable = value;
    },

    setLoading(state, value) {
      if (value) {
        state.loadingCount = state.loadingCount + 1;
      } else {
        state.loadingCount = state.loadingCount - 1;
      }
      state.loading = state.loadingCount !== 0;
    },

    setError(state, value) {
      console.log(value);
      state.error = value;
    },

    setUser(state, user) {
      state.authChecked = true;
      state.user = user;
    },

    setMediaQuery(state, data) {
      state.mediaQueries[data.mediaName] = data.value;
    }
  },
  actions: {
    logout({commit}) {
      return api.getLogout()
        .then(() => commit("setUser", null));
    }
  }
});