export const update = {
  getUpdate (updates, currentServerTime) {
    for (var i = updates.length - 1; i >= 0; i--) {
      if (updates[i].time <= currentServerTime) return i
    }
    return -1
  },
  interpolatePlayer (basePlayer, nextPlayer, dt) {
    var player = basePlayer
    player.x = basePlayer.x + (nextPlayer.x - basePlayer.x) * dt
    player.y = basePlayer.y + (nextPlayer.y - basePlayer.y) * dt
    // very bad
    player.angle = basePlayer.angle + (nextPlayer.angle - basePlayer.angle) * dt
    return player
  },
  computePlayers (updates, firstUpdateTime, gameStartTime) {
    console.log(updates)
    const currentServerTime = firstUpdateTime + (Date.now() - gameStartTime) - 100
    if (!updates) return []
    if (updates.length === 0) return []

    const baseUpdateIndex = this.getUpdate(updates, currentServerTime)
    if (baseUpdateIndex === -1) {
      return updates[updates.length - 1].players
    } else if (baseUpdateIndex === updates.length) {
      console.log('POUET')
      return updates[updates.length - 1].players
    } else {
      const baseUpdate = updates[baseUpdateIndex]
      const nextUpdate = updates[baseUpdateIndex + 1]
      const dt = (currentServerTime - baseUpdate.time) / (nextUpdate.time - baseUpdate.time)
      console.log('INTERPOLATION ' + dt)
      return baseUpdate.players.map(player => this.interpolatePlayer(player, nextUpdate.players.find(player2 => player.color === player2.color), dt))
    }
  }
}
