const state = {
  player: {
    x: 100,
    y: 100,
    angle: 0,
    targetAngle: 0,
    color: 'red',
    state: 'DEAD'
  },
  sprites: [],
  leaderboard: [],
  updates: [],
  firstUpdateTime: null,
  gameStartTime: null,
  settings: {
    playerSize: 10,
    playerSpeed: 2,
    playerTurnSpeed: 10,
    wallSize: 8,
    wallUpdate: 5,
    arenaSize: 1000
  },
  paused: true,
  socketConnected: false,
  loggedIn: false
}

const getters = {
}

const actions = {
  socketConnected ({ commit }, connected) {
    commit('SET_CONNECTED', connected)
    commit('CLEAR_UPDATE')
  },
  login ({ commit }, player) {
    commit('SET_PLAYER', player)
    commit('SET_LOGIN', true)
  },
  logout ({ commit }) {
    commit('SET_LOGIN', false)
    commit('CLEAR_UPDATE')
  },
  settings ({ commit }, settings) {
    commit('SET_SETTINGS', settings)
  },
  update ({ commit }, update) {
    commit('ADD_UPDATE', update)
    commit('SET_LEADERBOARD', update.players)
  },
  dead ({ commit }, player) {
    commit('SET_PLAYER', player)
    // commit('CLEAR_UPDATE')
  },
  spawn ({ commit }, player) {
    commit('SET_PLAYER', player)
    // commit('CLEAR_UPDATE')
  },
  error ({ commit }, error) {
    alert('Error: ' + error)
  }
}

const mutations = {
  SET_PLAYER (state, player) {
    state.player = player
  },
  SET_LOGIN (state, login) {
    state.loggedIn = login
  },
  SET_PLAYERS (state, players) {
    state.players = players
  },
  SET_SETTINGS (state, settings) {
    state.settings = settings
  },
  SET_PAUSE (state) {
    state.paused = !state.paused
  },
  SET_CONNECTED (state, connected) {
    state.socketConnected = connected
  },
  ADD_UPDATE (state, update) {
    if (state.updates.length === 0) {
      state.gameStartTime = Date.now()
      state.firstUpdateTime = update.time
    }

    if (state.updates.length > 2) {
      state.updates.shift()
    }
    state.updates.push(update)
  },
  CLEAR_UPDATE (state) {
    state.updates = []
  },
  SET_LEADERBOARD (state, players) {
    state.leaderboard = []

    if (!players) return

    players.forEach(player => {
      state.leaderboard.push({
        name: player.name,
        score: player.score,
        bestScore: player.bestScore,
        color: player.color
      })
    })

    state.leaderboard.sort((a, b) => {
      return b.score - a.score
    })
  }
}

export default {
  namespaced: true,
  state,
  getters,
  actions,
  mutations
}
