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.entity.npc.Alignment;
import common.entity.npc.PlayerCharacter;
import common.network.IClientPlayer;
import common.network.IPlayer;
import common.network.Packet;
import common.network.PacketBuffer;
import common.util.BlockPos;

public class SPacketCharacterList implements Packet<IClientPlayer> {
	private final Map<Integer, PlayerCharacter> players = Maps.newHashMap();
	
	private int selected;

	public SPacketCharacterList() {
	}

	public SPacketCharacterList(int selected) {
		this.selected = selected;
	}

	public SPacketCharacterList(int selected, int index, PlayerCharacter conns) {
		this.players.put(index, conns);
		this.selected = selected;
	}
	
	public SPacketCharacterList(int selected, Iterable<PlayerCharacter> conns) {
		int pos = 0;
		for(PlayerCharacter conn : conns) {
			this.players.put(pos++, conn);
		}
		this.selected = selected;
	}

	public void readPacketData(PacketBuffer buf) throws IOException {
		int n = buf.readVarInt();
		for(int z = 0; z < n; z++) {
			int id = buf.readVarInt();
			String name = buf.readString(IPlayer.MAX_NICK_LENGTH);
			if(name.isEmpty()) {
				this.players.put(id, null);
				continue;
			}
			String info = buf.readString(IPlayer.MAX_INFO_LENGTH);
			info = info.isEmpty() ? null : info;
			Alignment align = buf.readEnumValue(Alignment.class);
			String dim = buf.readString(256);
			BlockPos pos = buf.readBlockPos();
			String type = buf.readString(256);
			int level = buf.readVarInt();
			this.players.put(id, new PlayerCharacter(name, info, align, dim, pos, type, level));
		}
		this.selected = buf.readVarInt();
	}

	public void writePacketData(PacketBuffer buf) throws IOException {
		buf.writeVarInt(this.players.size());
		for(Entry<Integer, PlayerCharacter> data : this.players.entrySet()) {
			PlayerCharacter chr = data.getValue();
			buf.writeVarInt(data.getKey());
			if(chr == null) {
				buf.writeString("");
				continue;
			}
			buf.writeString(chr.name());
			buf.writeString(chr.info() == null ? "" : chr.info());
			buf.writeEnumValue(chr.align());
			buf.writeString(chr.dim());
			buf.writeBlockPos(chr.pos());
			buf.writeString(chr.type());
			buf.writeVarInt(chr.level());
		}
		buf.writeVarInt(this.selected);
	}

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

	public Collection<Entry<Integer, PlayerCharacter>> getEntries() {
		return this.players.entrySet();
	}
	
	public int getSelected() {
		return this.selected;
	}
}
