import axios from "axios";

export default {
    state: {
        session_token: null,
        connectionAvailable: false,
        exampleApi: axios.create({
            baseURL: process.env.VUE_APP_LOOPGRAFTER_DIRECT_API_MAPPING
                ? process.env.VUE_APP_LOOPGRAFTER_BACKEND_URL + "/exampleapi"
                : "api/exampleapi"
        }),
    },
    getters: {
        getApi(state, getters) {
            if (!getters.exampleMode) {
                return getters.getRealApi;
            } else {
                return state.exampleApi;
            }
        },

        getRealApi(state, getters) {
            return axios.create({
                baseURL: process.env.VUE_APP_LOOPGRAFTER_DIRECT_API_MAPPING
                    ? process.env.VUE_APP_LOOPGRAFTER_BACKEND_URL
                    : "api",
                params: { session_id: state.session_token }
            })
        },

        connected(state) {
            return state.connectionAvailable;
        },

        getToken(state) {
            return state.session_token
        }


    },
    mutations: {
        setConnectionAvailable(state, isAvailable) {
            state.connectionAvailable = isAvailable;

        },
        setToken(state, token) {
            state.session_token = token
        }
    },
    actions: {
        setToken(context, { token, override_example }) {
            if (!override_example && context.getters.exampleMode) {
                context.commit('setToken', "exemplary-example")
                return
            }
            if (token == "exemplary-example") {
                context.commit('setExampleMode', true);
            } else {
                context.commit('setExampleMode', false);
            }
            context.commit('setToken', token)

        },
        ping(context) {
            if (context.state.session_token == null) {
                context.dispatch("getToken") //don't need to wait for ping
            }

            return context.getters.getApi.get('/heartbeat').then(resp => {
                if (resp.data.message != 'beat') {
                    throw 'Not beat';
                }
                context.commit('setConnectionAvailable', true);
            }).catch(() => context.commit('setConnectionAvailable', false))
        },

        getToken(context) {
            return context.getters.getApi.get('/gettoken').then(resp => {
                context.dispatch('setToken', { token: resp.data.token });
            })
        }
    }
}