import Vuex from 'vuex'
import Vue from 'vue'
import ServerService from '../services/Server'
import UserService from '../services/User'

Vue.use(Vuex)

export default new Vuex.Store({
    state: {
        settingsLoaded: false,
        loggedIn : false,
        meLoaded: false,
        me: [],
        redirectIfLoggedIn: null,
        settings: [], // The TV inventory
        sideMenu: false, //Toggle Side Menu on side Bar,
        error: false
    },

    getters: {
        // Here we will create a getter
        getSettingValue: (state) => (name) => {
            if(state.settingsLoaded == false) {
                return null;
            }
            for(var i = 0; i < state.settings.length; i++) {
                if(state.settings[i]["name"] == name) {
                    return state.settings[i]["value"];
                }
            }
        },
        getAllDataLoaded: (state) => {
            var loaded = true;
            if(!state.meLoaded) {
                loaded = false;
            }
            if(!state.settingsLoaded) {
                loaded = false;
            }
            return loaded;
        },
        getError: (state) => {
            return state.error
        },
        getMe: (state) => {
            return state.me;
        }
    },

    mutations: {
        setSettings: function(state, settings) {
            state.settings = settings;
            state.settingsLoaded = true;
        },
        setError: function(state) {
          state.error = true;
        },
        setMe: function(state, me) {
            if(me == false) {
                state.loggedIn = false;
                state.meLoaded = true;
            } else {
                state.me = me;
                state.loggedIn = true;
                state.meLoaded = true;
            }
        },

    },

    actions: {
        getSettings: function (context) {
            return new Promise((resolve, reject) => {
                ServerService.getPublicSettings().then((res) => {
                    context.commit('setSettings', res.data.data)
                    resolve()
                }).catch((res) => {
                    context.commit('setError')
                });
            })
        },
        checkAccount: function(context) {
            UserService.getTokenFromStorage();
            return new Promise((resolve, reject) => {
                UserService.me().then((res) => {
                    context.commit('setMe', res.data.data)
                }, (res) => {
                    context.commit('setMe', false)
                })
            })
        }
    }
});
