package common.packet;

import java.io.IOException;
import java.util.Collection;
import java.util.Map;
import java.util.Map.Entry;

import common.collect.Maps;
import common.network.IClientPlayer;
import common.network.IPlayer;
import common.network.Packet;
import common.network.PacketBuffer;

public class SPacketPlayerListItem implements Packet<IClientPlayer> {
	private final Map<String, Integer> players = Maps.newHashMap();

	public SPacketPlayerListItem() {
	}

	public SPacketPlayerListItem(boolean remove, IPlayer... conns) {
		for(IPlayer conn : conns) {
			this.players.put(conn.getUser(), remove ? -1 : conn.getLatency());
		}
	}

	public SPacketPlayerListItem(Iterable<IPlayer> conns) {
		for(IPlayer conn : conns) {
			this.players.put(((IPlayer)conn).getUser(), ((IPlayer)conn).getLatency());
		}
	}

	public void readPacketData(PacketBuffer buf) throws IOException {
		int n = buf.readVarInt();
		for(int z = 0; z < n; z++) {
			this.players.put(buf.readString(16), buf.readVarInt());
		}
	}

	public void writePacketData(PacketBuffer buf) throws IOException {
		buf.writeVarInt(this.players.size());
		for(Entry<String, Integer> data : this.players.entrySet()) {
			buf.writeString(data.getKey());
			buf.writeVarInt(data.getValue());
		}
	}

	public void processPacket(IClientPlayer handler) {
		handler.handlePlayerListItem(this);
	}

	public Collection<Entry<String, Integer>> getEntries() {
		return this.players.entrySet();
	}
}
