package net.minecraft.src;

import java.io.*;
import java.util.*;
import net.minecraft.client.Minecraft;
import net.minecraft.src.atomicstryker.ForgePacketWrapper;
import net.minecraft.src.atomicstryker.battletowers.*;
import net.minecraft.src.forge.*;

public class mod_AS_BattleTowers extends NetworkMod implements IConnectionHandler, IPacketHandler
{
	private long time;
	private MovingObjectPosition playerTarget;
	private boolean hackFailed;
	public static AS_BattleTowersCore coreInstance;

	public mod_AS_BattleTowers()
	{
		coreInstance = new AS_BattleTowersCore();
	}
	
	@Override
	public void load()
	{
		if (coreInstance == null)
		{
			coreInstance = new AS_BattleTowersCore();
		}
		coreInstance.load(this);

		time = System.currentTimeMillis();
		ModLoader.setInGameHook(this, true, true);
	}

	@Override
	public void onPacketData(NetworkManager network, String channel, byte[] bytes)
	{
		DataInputStream data = new DataInputStream(new ByteArrayInputStream(bytes));

		int packetID = ForgePacketWrapper.readPacketID(data);

		if (packetID == 1)
		{
			Class[] decodeAs = { Integer.class };
			Object[] packetReadout = ForgePacketWrapper.readPacketData(data, decodeAs);

			coreInstance.towerDestroyerEnabled = (Integer) packetReadout[0];
		}
	}

	@Override
	public boolean onTickInGame(float derp, net.minecraft.client.Minecraft mc)
	{
		if (mc.thePlayer == null || mc.theWorld == null)
			return true;

		if (System.currentTimeMillis() > time + 1000L) // its a one second timer
														// OMFG
		{
			coreInstance.onNewInGameSecond();
		}
		
		if (mc.currentScreen != null
		&& mc.currentScreen instanceof GuiChest)
		{
			List ents = mc.theWorld.getEntitiesWithinAABBExcludingEntity(mc.thePlayer, AxisAlignedBB.getBoundingBox(mc.thePlayer.posX - 8D, mc.thePlayer.posY - 8D, mc.thePlayer.posZ - 8D, mc.thePlayer.posX + 8D, mc.thePlayer.posY + 8D, mc.thePlayer.posZ + 8D));
			if (!ents.isEmpty())
			{
				for (int i = ents.size() - 1; i >= 0; i--)
				{
					if (ents.get(i) instanceof AS_EntityGolem)
					{
						boolean multiplayer = mc.theWorld.isRemote;
						
						AS_EntityGolem golem = (AS_EntityGolem) ents.get(i);
						
						if (multiplayer)
						{
							Object[] objArray = { golem.entityId };
							ModLoader.sendPacket(ForgePacketWrapper.createPacket(coreInstance.getPacketChannelName(), 2, objArray));
						}
						else
						{
							golem.setAwake();
						}
						
						mc.displayGuiScreen(null);
						break;
					}
				}
			}
		}

		if (!hackFailed && mc.objectMouseOver != null && mc.objectMouseOver.typeOfHit == EnumMovingObjectType.TILE && mc.objectMouseOver != playerTarget)
		{
			playerTarget = mc.objectMouseOver;

			int x = playerTarget.blockX;
			int y = playerTarget.blockY;
			int z = playerTarget.blockZ;

			if (mc.theWorld.getBlockId(x, y, z) == Block.chest.blockID)
			{
				List ents = mc.theWorld.getEntitiesWithinAABBExcludingEntity(mc.thePlayer, AxisAlignedBB.getBoundingBox(x - 7D, y - 7D, z - 7D, x + 7D, y + 7D, z + 7D));
				if (!ents.isEmpty())
				{
					for (int i = ents.size() - 1; i >= 0; i--)
					{
						if (ents.get(i) instanceof AS_EntityGolem)
						{
							boolean multiplayer = mc.theWorld.isRemote;

							AS_EntityGolem golem = (AS_EntityGolem) ents.get(i);
							Object progressHack = null;
							float progress = 0;
							try
							{
								progressHack = ModLoader.getPrivateValue(multiplayer ? PlayerControllerMP.class : PlayerControllerSP.class, mc.playerController, 3);
								progress = (Float) progressHack;
							}
							catch (Exception e)
							{
								System.err.println("Tell AtomicStryker to update his BattleTowers Block Break Progress Hack because: " + e);
								hackFailed = true;
								e.printStackTrace();
							}

							if (progress > 0)
							{
								if (multiplayer)
								{
									Object[] objArray = { golem.entityId };
									ModLoader.sendPacket(ForgePacketWrapper.createPacket(coreInstance.getPacketChannelName(), 2, objArray));
								}
								else
								{
									golem.setAwake();
								}
							}

							break;
						}
					}
				}
			}
		}

		return true;
	}

	@Override
	public void modsLoaded()
	{
		System.err.println("BATTLE TOWERS CONFIG");
		System.err.println((new StringBuilder()).append("Tower Rarity ").append(String.valueOf(coreInstance.rarity)).toString());
		System.err.println((new StringBuilder()).append("Min Tower Distance ").append(String.valueOf(coreInstance.minDistanceBetweenTowers)).toString());
		System.err.println((new StringBuilder()).append("MINECRAFT PROPERTIES ").append(String.valueOf(coreInstance.configpath)).toString());
	}

	@Override
	public void addRenderer(Map map)
	{
		map.put(net.minecraft.src.atomicstryker.battletowers.AS_EntityGolem.class, new AS_RenderGolem());
	}

	@Override
	public void generateSurface(World world, Random random, int x, int z)
	{
		coreInstance.generateSurface(world, random, x, z);
	}

	@Override
	public String getVersion()
	{		
		return coreInstance.getVersion();
	}

	@Override
	public boolean clientSideRequired()
	{
		return true;
	}

	@Override
	public boolean serverSideRequired()
	{
		return false;
	}

	@Override
	public void onConnect(NetworkManager network)
	{
		MessageManager.getInstance().registerChannel(network, this, coreInstance.getPacketChannelName());
	}

	@Override
	public void onLogin(NetworkManager network, Packet1Login login)
	{
	}

	@Override
	public void onDisconnect(NetworkManager network, String message, Object[] args)
	{
	}

	public static File getMinecraftDir()
	{
		return Minecraft.getMinecraftDir();
	}

	public static void onBattleTowerDestroyed(AS_TowerDestroyer td)
	{
		ModLoader.getMinecraftInstance().ingameGUI.addChatMessage("The Battletower's Guardian has fallen! Without it's power, the Tower will collapse...");
	}
}
