import Vue from "vue";
import Vuex from "vuex";

Vue.use(Vuex);

export const store = new Vuex.Store({
  state: {
    isConnected: false,
    name: "Menteur inconnu",
    text: "none",
    socketMessage: "",
    gameState: "RESET",
    cards: [],
    players: []
  },
  getters: {
    isConnected: state => state.isConnected,
    name: state => state.name,
    socketMessage: state => state.socketMessage,
    gameState: state => state.gameState,
    cards: state => state.cards,
    players: state => state.players,
    gamers: state => state.players.filter(p => p.isPlaying)
  },
  mutations: {
    SOCKET_CONNECT(state) {
      state.isConnected = true;
    },

    SOCKET_DISCONNECT(state) {
      state.isConnected = false;
    },
    SOCKET_MESSAGECHANNEL(state, message) {
      state.socketMessage = message;
      console.log("SMC| Current state now:", state.socketMessage);
    },
    name(state, name) {
      state.name = name;
    },
    text(state, text) {
      state.text = text;
    },
    gameState(state, gameState) {
      state.gameState = gameState;
    },
    cards(state, cards) {
      state.cards = cards;
    },
    message(state, message) {
      state.socketMessage = message;
      console.log("storeMess| Current message now:" + JSON.stringify(message));
      if (message) {
        if (message.data) {
          let players = message.data.players;
          let cards = message.data.cards;
          let gameState = message.data.state;
          let extras = message.data.extras;
          if (players) {
            // console.log("Setting players:", players);
            state.players = players;
          }
          if (gameState) {
            // console.log("Setting state:", gameState);
            state.state = gameState;
          }
          if (cards) {
            // console.log("Setting cards:", cards);
            state.cards = cards;
          }
          if (extras) {
            console.log("Extras: ", JSON.stringify(extras));
            let name = extras.name;
            let text = extras.text;

            if (name) {
              state.name = name;
            }
            if (text) {
              state.text = text;
            }
          }

        }
      }
    }
  }
});
