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 S38PacketPlayerListItem implements Packet<IClientPlayer> {
	private final Map<String, Integer> players = Maps.newHashMap();

	public S38PacketPlayerListItem() {
	}

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

	public S38PacketPlayerListItem(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.readVarIntFromBuffer();
		for(int z = 0; z < n; z++) {
			this.players.put(buf.readStringFromBuffer(16), buf.readVarIntFromBuffer());
		}
	}

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

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

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