package ncrashed.registration;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
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.CompressedStreamTools;
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 CommandClearInventory  extends CommandBase implements ICommand 
{
	@Override
	public String getCommandName() 
	{
		return "invclear";
	}

    public int getRequiredPermissionLevel()
    {
        return 2;
    }
    
	@Override
	public String getCommandUsage(ICommandSender var1) 
	{	
		return "/invclear <player> <itemid> - Removes items with itemid from player inventory.";
	}

	@Override
	public void processCommand(ICommandSender sender, String[] pars) 
	{
		if(pars.length < 3) return;
		String playerName = pars[0];
		Integer itemId = Integer.parseInt(pars[1]);
		Integer itemMeta = Integer.parseInt(pars[2]);
		
		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))
				{
					player.inventory.clearInventory(itemId, itemMeta);
					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);
					
					int res = inv.clearInventory(itemId, itemMeta);
					
					playerTag.setTag("Inventory", inv.writeToNBT(new NBTTagList()));
		            
					File playersDirectory = new File(sh.getWorldDirectory(), "players");
		            File newFile = new File(playersDirectory, playerName + ".dat.tmp");
		            File oldFile = new File(playersDirectory, playerName + ".dat");
		            try {
						CompressedStreamTools.writeCompressed(playerTag, new FileOutputStream(newFile));
					} catch (IOException e)
					{
						//sender.sendChatToPlayer("Failed to save results!");
						return;
					}

		            if (oldFile.exists())
		            {
		                oldFile.delete();
		            }

		            newFile.renameTo(oldFile);
		            
					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);
		            //sender.sendChatToPlayer("Cleared "+res+" items!");
					return;
				}
			}
		}
		
		//sender.sendChatToPlayer("Cannot find player "+playerName);
	}
}
