'use strict';
import Vue from 'vue';
import Vuex from 'vuex';

Vue.use(Vuex);

import menu from './menu/menu';
import game from './game/game';
import { socketService } from '../main';

const state = {
  username: '',
  isConnected: false,
  gameId: -1,
  isGameRunning: false,
  messages: []
};

/**
 * The module 'getters' object.
 *
 * @name Getters
 * @type {object}
 * @getter {Array<string>} messages=messages Returns the messages for chat.
 * @getter {number} gameId=gameId Returns the id of current online game playing (-1 if no online game).
 * @getter {boolean} isGameRunning=isGameRunning Returns true if a game is running (online or local).
 */
const getters = {
  messages(state) {
    return state.messages;
  },
  gameId(state) {
    return state.gameId;
  },
  isGameRunning(state) {
    return state.isGameRunning;
  },
  username(state) {
    return state.username;
  },
  isConnected(state) {
    return state.isConnected;
  }
};

const mutations = {
  ADD_MESSAGE: (state, payload) => {
    state.messages.push(payload);
  },
  SET_GAME_ID: (state, payload) => {
    state.gameId = payload;
  },
  SET_IS_GAME_RUNNING: (state, payload) => {
    state.isGameRunning = payload;
  },
  SET_USERNAME: (state, payload) => {
    state.username = payload;
  },
  SET_IS_CONNECTED: (state, payload) => {
    state.isConnected = payload;
  }
};
const actions = {
  addMessageToQueue: ({ commit }, payload) => {
    commit('ADD_MESSAGE', payload);
  },
  stopGame: ({ commit, rootState }) => {
    socketService.leaveGame(rootState.username);
    commit('SET_IS_GAME_RUNNING', false);
    localStorage.removeItem('gameId');
  },
  disconnect: ({ commit }) => {
    socketService.disconnect();
    commit('SET_GAME_ID', -1);
    commit('SET_IS_GAME_RUNNING', false);
    commit('SET_USERNAME', '');
    commit('SET_IS_CONNECTED', false);
    commit('menu/RESET_ALL_STATUS');
    localStorage.removeItem('username');
    localStorage.removeItem('gameId');
  }
};

export const store = new Vuex.Store({
  state,
  getters,
  mutations,
  actions,

  modules: {
    menu,
    game
  }
});