import Vue from 'vue';
import Vuex, { Store } from "vuex";
import Services from '../services';

Vue.use(Vuex);
const store = new Store({
  strict: true,
  state: {
    inCall: false,
    user: { name: 'loading...', is_admin: false, id: null, books: [] },
    notifications: []
  },
  getters: {
    user(state) {
      return state.user;
    },
    notifications(state) {
      return state.notifications;
    },
    inCall(state) {
      return state.inCall;
    }
  },
  mutations: {
    setUser(state, user) {
      state.user = user;
    },
    notify(state, notification) {
      const id = Math.ceil(Math.random() * 1000);
      state.notifications.push({ ...notification, id });
      const dispatch = this.dispatch;
      setTimeout(() => {
        dispatch("dismissNotification", id);
      }, 5000);
    },
    dismissNotification(state, noteId: number) {
      state.notifications = state.notifications.filter(n => n.id != noteId);
    },
    callEnded(state) {
      state.inCall = false;
    },
    callStarted(state) {
      state.inCall = true;
    }
  },
  actions: {
    async getUser(ctx, userId?: number) {
      const user = await Services.ApiService.getUser(userId);
      ctx.commit('setUser', user);
      return user;
    },
    notify(ctx, notification: { message: string, level?: "info" | "warning" | "success" | "danger" }) {
      ctx.commit("notify", notification);
    },
    dismissNotification(ctx, id: number) {
      ctx.commit("dismissNotification", id);
    },
    callEnded(ctx) {
      ctx.commit('callEnded');
    },
    callStarted(ctx) {
      ctx.commit('callStarted');
    }
  }
});
export default store;
