import { Module, MutationTree, ActionTree, GetterTree } from 'vuex';
import { StateInterface } from 'src/store';
import { axios } from 'boot/axios';
import { LoginData } from 'src/plugins/user/models';
import { AxiosResponse } from 'axios';
import { LocalStorage } from 'quasar';
import { Router } from 'src/router';

export interface SessionInterface {
  sessions: Session[];
  loading: boolean;
}
export interface Session {
  browser: string;
  expires: string;
  lifetime: number;
  platform: string;
  token: string;
}
const state: SessionInterface = {
  sessions: [],
  loading: false
};

const mutations: MutationTree<SessionInterface> = {
  setSessions(state, sessions: Session[]) {
    state.sessions = sessions;
  },
  setLoading(state, value: boolean) {
    state.loading = value;
  }
};

const actions: ActionTree<SessionInterface, StateInterface> = {
  getSessions({ commit, rootGetters }) {
    console.log(rootGetters);
    commit('setLoading', true);
    axios
      .get('http://localhost:5000/auth', {
        headers: { Token: rootGetters['user/token'].token }
      })
      .then(response => {
        console.log(response.data);
        commit('setSessions', response.data);
      })
      .catch(error => {
        console.exception(error);
      })
      .finally(() => {
        commit('setLoading', false);
      });
  },
  deleteSession({ commit, dispatch, rootGetters }, token) {
    commit('setLoading', true);
    axios
      .delete(`http://localhost:5000/auth/${token}`, {
        headers: { Token: rootGetters['user/token'].token }
      })
      .then(() => {
        void dispatch('getSessions');
      })
      .catch(error => {
        console.exception();
      })
      .finally(() => {
        commit('setLoading', false);
      });
  }
};

const getters: GetterTree<SessionInterface, StateInterface> = {
  sessions(state) {
    return state.sessions;
  },
  loading(state) {
    return state.loading;
  }
};

const sessions: Module<SessionInterface, StateInterface> = {
  namespaced: true,
  state,
  mutations,
  actions,
  getters
};

export default sessions;