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

export interface SessionInterface {
  currentSession?: FG.Session;
  sessions: FG.Session[];
  loading: boolean;
}

const state: SessionInterface = {
  sessions: [],
  currentSession:
    LocalStorage.getItem<FG.Session>('currentSession') || undefined,
  loading: false
};

const mutations: MutationTree<SessionInterface> = {
  setCurrentSession(state, session: FG.Session) {
    LocalStorage.set('currentSession', session);
    state.currentSession = session;
  },
  clearCurrentSession(state) {
    LocalStorage.remove('currentSession');
    state.currentSession = undefined;
  },
  setSessions(state, sessions: FG.Session[]) {
    state.sessions = sessions;
  },
  setLoading(state, value: boolean) {
    state.loading = value;
  }
};

const actions: ActionTree<SessionInterface, StateInterface> = {
  login({ commit }, data: LoginData) {
    Loading.show({
      message: 'Du wirst angemeldet'
    });
    void axios
      .post('/auth', data)
      .then((response: AxiosResponse<LoginResponse>) => {
        response.data.session.expires = new Date(response.data.session.expires);
        commit('setCurrentSession', response.data.session);
        commit('user/setCurrentUser', response.data.user, { root: true });
        void Router.push({ name: 'user-main' });
      })
      .catch(error => {
        console.exception(error);
      })
      .finally(() => {
        Loading.hide();
      });
  },
  /**
   * Logout from current session
   */
  logout({ dispatch, rootState }) {
    Loading.show({ message: 'Session wird abgemeldet' });
    dispatch('deleteSession', rootState.session.currentSession?.token).finally(
      () => {
        Loading.hide();
      }
    );
  },
  /**
   * Delete a given session
   */
  deleteSession({ commit, rootState }, token: string | null) {
    if (token === null) return;

    commit('setLoading', true);
    axios
      .delete(`/auth/${token}`)
      .then(() => {
        if (token === rootState.session.currentSession?.token) {
          commit('clearCurrentSession');
          commit('user/clearCurrentUser', null, { root: true });
          void Router.push({ name: 'login' });
        } else {
          commit('getSessions');
        }
      })
      .finally(() => {
        commit('setLoading', false);
      });
  },
  /**
   * Get all sessions from current User
   */
  getSessions({ commit, state, dispatch }) {
    commit('setLoading', true);
    axios
      .get('/auth')
      .then((response: AxiosResponse<FG.Session[]>) => {
        response.data.forEach(session => {
          session.expires = new Date(session.expires);
        });
        commit('setSessions', response.data);
        const currentSession = response.data.find((session: FG.Session) => {
          return session.token === state.currentSession?.token;
        });
        if (currentSession) {
          void dispatch('setCurrentSession', currentSession);
        }
      })
      .catch(error => {
        console.exception(error);
      })
      .finally(() => {
        commit('setLoading', false);
      });
  }
};

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

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

export default sessions;