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

const getters = {
  // Interpolation position des joueurs
  currentPlayers: state => {
    if (state.updates.length < 2) return state.updates[0].players
    else {
      const dt = state.updates[0].time - state.updates[1].time
      return state.updates[1].players.map(player => interpolatePlayer(player, dt))
    }
  }
}

const actions = {
  socketConnected ({ commit }) {
    commit('SET_CONNECTED')
    commit('CLEAR_UPDATE')
  },
  login ({ commit }, player) {
    commit('SET_PLAYER', player)
  },
  settings ({ commit }, settings) {
    commit('SET_SETTINGS', settings)
  },
  update ({ commit }, update) {
    commit('ADD_UPDATE', update)
  },
  dead ({ 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_PLAYERS (state, players) {
    state.players = players
  },
  SET_SETTINGS (state, settings) {
    state.settings = settings
  },
  SET_PAUSE (state) {
    state.paused = !state.paused
  },
  SET_CONNECTED (state) {
    state.socketConnected = !state.socketConnected
  },
  ADD_UPDATE (state, update) {
    if (state.updates.length > 2) {
      state.updates.shift()
    }
    update.time = update.time.epochSecond
    state.updates.push(update)
  },
  CLEAR_UPDATE (state) {
    state.updates = []
  }
}

function interpolatePlayer (player, dt) {
  return player
}

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