package ncrashed.registration;

import java.util.List;

import cpw.mods.fml.common.FMLCommonHandler;

import net.minecraft.command.CommandBase;
import net.minecraft.command.ICommand;
import net.minecraft.command.ICommandSender;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.entity.player.InventoryPlayer;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.nbt.NBTTagList;
import net.minecraft.server.MinecraftServer;
import net.minecraft.world.WorldServer;
import net.minecraft.world.storage.ISaveHandler;
import net.minecraft.world.storage.SaveHandler;

public class CommandSpawnProtection  extends CommandBase implements ICommand 
{
	@Override
	public String getCommandName() 
	{
		return "invshow";
	}

    public int getRequiredPermissionLevel()
    {
        return 2;
    }
    
	@Override
	public String getCommandUsage(ICommandSender var1) 
	{	
		return "/invshow <player> - Shows inventory of the player.";
	}

	@Override
	public void processCommand(ICommandSender sender, String[] pars) 
	{
		if(pars.length == 0) return;
		String playerName = pars[0];
		
		MinecraftServer server = FMLCommonHandler.instance().getMinecraftServerInstance();
		for(int i = 0; i < server.worldServers.length; i++)
		{
			WorldServer worldServer = server.worldServers[i];
			for(int j = 0; j < worldServer.playerEntities.size(); j++)
			{
				EntityPlayerMP player = (EntityPlayerMP)worldServer.playerEntities.get(j);
				if(player.username.equals(playerName))
				{
					String buff = "";
					for(int z = 0; z < player.inventory.getSizeInventory(); z++)
					{
						ItemStack stack = player.inventory.getStackInSlot(z);
						if(stack != null)
							buff += stack.itemID+"("+stack.stackSize+") ";
					}
					sender.sendChatToPlayer(buff);
					return;
				}
			}
		}
		
		ISaveHandler handler = server.worldServers[0].getSaveHandler();
		if(handler instanceof SaveHandler)
		{
			SaveHandler sh = ((SaveHandler) handler);
			String[] players = sh.getAvailablePlayerDat();
			for(int i = 0; i < players.length; i++)
			{
				sender.sendChatToPlayer("Checking "+players[i]);
				if(players[i].equals(playerName))
				{
					sender.sendChatToPlayer("Player data finded");
					NBTTagCompound playerTag = sh.getPlayerData(players[i]);
					NBTTagList invTagList = playerTag.getTagList("Inventory");
					InventoryPlayer inv = new InventoryPlayer(null);
					inv.readFromNBT(invTagList);
					
					String buff = "";
					for(int z = 0; z < inv.getSizeInventory(); z++)
					{
						ItemStack stack = inv.getStackInSlot(z);
						if(stack != null)
							buff += stack.itemID+"("+stack.stackSize+") ";
					}
					sender.sendChatToPlayer(buff);
					
					return;
				}
			}
		}
		
		sender.sendChatToPlayer("Cannot find player "+playerName);
	}
}
