/*
 * This program is free software: you can redistribute it and/or modify it under
 * the terms of the GNU General Public License as published by the Free Software
 * Foundation, either version 3 of the License, or (at your option) any later
 * version.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
 * details.
 *
 * You should have received a copy of the GNU General Public License along with
 * this program. If not, see <http://www.gnu.org/licenses/>.
 */
package net.sf.l2j.gameserver.network.clientpackets;

import java.util.logging.Level;
import java.util.logging.Logger;

import net.sf.l2j.Config;
import net.sf.l2j.gameserver.ai.CtrlIntention;
import net.sf.l2j.gameserver.communitybbs.CommunityBoard;
import net.sf.l2j.gameserver.handler.AdminCommandHandler;
import net.sf.l2j.gameserver.handler.IAdminCommandHandler;
import net.sf.l2j.gameserver.model.L2CharPosition;
import net.sf.l2j.gameserver.model.L2Object;
import net.sf.l2j.gameserver.model.L2World;
import net.sf.l2j.gameserver.model.actor.instance.L2ClassMasterInstance;
import net.sf.l2j.gameserver.model.actor.instance.L2NpcInstance;
import net.sf.l2j.gameserver.model.actor.instance.L2PcInstance;
import net.sf.l2j.gameserver.model.entity.L2Event;
import net.sf.l2j.gameserver.model.entity.L2JOneoRusEvents.CTF;
import net.sf.l2j.gameserver.model.entity.L2JOneoRusEvents.DM;
import net.sf.l2j.gameserver.model.entity.L2JOneoRusEvents.FortressSiege;
import net.sf.l2j.gameserver.model.entity.L2JOneoRusEvents.TvT;
import net.sf.l2j.gameserver.network.serverpackets.ActionFailed;
import net.sf.l2j.gameserver.network.serverpackets.NpcHtmlMessage;
import net.sf.l2j.gameserver.cache.HtmCache;
import net.sf.l2j.gameserver.datatables.SkillTable;
import net.sf.l2j.gameserver.model.L2Skill;
import net.sf.l2j.gameserver.network.SystemMessageId;
import net.sf.l2j.gameserver.network.serverpackets.InventoryUpdate;
import net.sf.l2j.gameserver.network.serverpackets.MagicSkillUser;
import net.sf.l2j.gameserver.network.serverpackets.SystemMessage;
import net.sf.l2j.gameserver.network.serverpackets.WareHouseDepositList;
import net.sf.l2j.gameserver.network.serverpackets.WareHouseWithdrawalList;

/**
 * This class ...
 *
 * @version $Revision: 1.12.4.5 $ $Date: 2005/04/11 10:06:11 $
 */
public final class RequestBypassToServer extends L2GameClientPacket
{
	private static final String _C__21_REQUESTBYPASSTOSERVER = "[C] 21 RequestBypassToServer";
	private static Logger _log = Logger.getLogger(RequestBypassToServer.class.getName());
	// S
	private String _command;

	/**
	 * @param decrypt
	 */
	@Override
	protected void readImpl()
	{
		_command = readS();
	}

	@Override
	protected void runImpl()
	{
		L2PcInstance activeChar = getClient().getActiveChar();
		if (!activeChar.getFloodProtectors().getServerBypass().tryPerformAction("_command"))
		{
			activeChar.sendPacket(ActionFailed.STATIC_PACKET);
			return;
		}
		if (activeChar == null)
		{
			return;
		}
		try
		{
			if (_command.startsWith("admin_")) // &&
			// activeChar.getAccessLevel()
			// >= Config.GM_ACCESSLEVEL)
			{
				if (Config.ALT_PRIVILEGES_ADMIN && !AdminCommandHandler.getInstance().checkPrivileges(activeChar, _command))
				{
					_log.info("<GM>" + activeChar + " does not have sufficient privileges for command '" + _command + "'.");
					return;
				}
				IAdminCommandHandler ach = AdminCommandHandler.getInstance().getAdminCommandHandler(_command);
				if (ach != null)
				{
					ach.useAdminCommand(_command, activeChar);
				}
				else
				{
					_log.warning("No handler registered for bypass '" + _command + "'");
				}
			}
			else if (_command.equals("come_here") && activeChar.getAccessLevel() >= Config.GM_ACCESSLEVEL)
			{
				comeHere(activeChar);
			}
			else if (_command.startsWith("wh_deposit"))
							{
								if (Config.ENABLE_VCAIO_WH)
								{
									activeChar.sendPacket(new ActionFailed());
									activeChar.setActiveWarehouse(activeChar.getWarehouse());
									activeChar.tempInvetoryDisable();
				
									if (Config.DEBUG)
										_log.fine("Showing items to deposit");
				
									activeChar.sendPacket(new WareHouseDepositList(activeChar, WareHouseDepositList.PRIVATE));
								}
							}
							else if (_command.startsWith("aio_linktoshop"))
							{
								if (Config.ENABLE_VCAIO_SHOP)
								{
									String htmFile = "data/html/mods/VoicedAIOMiniShop.htm";
					        		String htmContent = HtmCache.getInstance().getHtm(htmFile);
					        		if (htmContent != null)
					        		{
					        			NpcHtmlMessage infoHtml = new NpcHtmlMessage(1);
					        			infoHtml.setHtml(htmContent);
					        			activeChar.sendPacket(infoHtml);
					        		}
								}
							}
							else if (_command.startsWith("wh_withdraw"))
							{
								if (Config.ENABLE_VCAIO_WH)
								{
									activeChar.sendPacket(new ActionFailed());
									activeChar.setActiveWarehouse(activeChar.getWarehouse());
									activeChar.tempInvetoryDisable();
				
									if (activeChar.getActiveWarehouse().getSize() == 0)
									{
										activeChar.sendPacket(new SystemMessage(SystemMessageId.NO_ITEM_DEPOSITED_IN_WH));
										return;
									}
				
									if (Config.DEBUG)
										_log.fine("Showing stored items");
				
									activeChar.sendPacket(new WareHouseWithdrawalList(activeChar, WareHouseWithdrawalList.PRIVATE));
								}
							}
							else if (_command.startsWith("aio_teleportarea"))
							{
								if (Config.ENABLE_VCAIO_TPNRT)
								{
									activeChar.teleToLocation(Config.AIOTP_X, Config.AIOTP_Y, Config.AIOTP_Z, true);
								}
							}
							else if (_command.startsWith("aio_minishop"))
							{
								if (Config.ENABLE_VCAIO_SHOP)
								{
				                                       if (activeChar.getInventory().getInventoryItemCount(57, 0) >= Config.VCAIO_MINISHOP_ADENAS)
								        {
									        InventoryUpdate iup = new InventoryUpdate();
									        activeChar.getInventory().reduceAdena("Item", Config.VCAIO_MINISHOP_ADENAS, activeChar, null);
									        activeChar.getInventory().addItem("Item", Config.VCAIO_MINISHOP_ITEMID, Config.VCAIO_MINISHOP_ITEMAMMOUNT, activeChar, null);
									        activeChar.getInventory().updateDatabase();
									        activeChar.sendPacket(iup);
				                                       }
				                                       else
								        {
								                activeChar.sendMessage("You do not have enough adena to use this function!");
								        }
								}
							}
							else if (_command.startsWith("aio_infos"))
							{
								if (Config.ENABLE_VCAIO_INFOS)
								{
									String htmFile = "data/html/mods/VCAioInfos.htm";
					        		String htmContent = HtmCache.getInstance().getHtm(htmFile);
					        		if (htmContent != null)
					        		{
					        			NpcHtmlMessage infoHtml = new NpcHtmlMessage(1);
					        			infoHtml.setHtml(htmContent);
					        			activeChar.sendPacket(infoHtml);
					        		}
								}
							}
							else if (_command.startsWith("aio_buffing"))
							{
								if (Config.ENABLE_AIO_BUFFING)
								{
									L2Skill skill;
									// Fighter Buffs
									if (!activeChar.isMageClass())
									{
										// There are 3 buffs for now, although you can add even more if you follow the same steps.
										skill = SkillTable.getInstance().getInfo(Config.AIO_FBUFF_1, Config.AIO_FBUFF_1_LVL);
										skill.getEffects(activeChar, activeChar);
											activeChar.broadcastPacket(new MagicSkillUser(activeChar, activeChar, skill.getId(), 1, skill.getHitTime(), 0));
										skill = SkillTable.getInstance().getInfo(Config.AIO_FBUFF_2, Config.AIO_FBUFF_2_LVL);
										skill.getEffects(activeChar, activeChar);
											activeChar.broadcastPacket(new MagicSkillUser(activeChar, activeChar, skill.getId(), 1, skill.getHitTime(), 0));
										skill = SkillTable.getInstance().getInfo(Config.AIO_FBUFF_3, Config.AIO_FBUFF_3_LVL);
										skill.getEffects(activeChar, activeChar);
											activeChar.broadcastPacket(new MagicSkillUser(activeChar, activeChar, skill.getId(), 1, skill.getHitTime(), 0));
									}
									// Mage Buffs
									else if (activeChar.isMageClass())
								{
										// There are 3 buffs for now, although you can add even more if you follow the same steps.
										skill = SkillTable.getInstance().getInfo(Config.AIO_MBUFF_1, Config.AIO_MBUFF_1_LVL);
										skill.getEffects(activeChar, activeChar);
				                         activeChar.broadcastPacket(new MagicSkillUser(activeChar, activeChar, skill.getId(), 1, skill.getHitTime(), 0));             
					                    skill = SkillTable.getInstance().getInfo(Config.AIO_MBUFF_1, Config.AIO_MBUFF_2_LVL);
					                    skill.getEffects(activeChar, activeChar);
					                         activeChar.broadcastPacket(new MagicSkillUser(activeChar, activeChar, skill.getId(), 1, skill.getHitTime(), 0));              
					                    skill = SkillTable.getInstance().getInfo(Config.AIO_MBUFF_1, Config.AIO_MBUFF_3_LVL);
					                    skill.getEffects(activeChar, activeChar);
					                         activeChar.broadcastPacket(new MagicSkillUser(activeChar, activeChar, skill.getId(), 1, skill.getHitTime(), 0));                
									}
								}
							}
			else if (_command.startsWith("player_help "))
			{
				playerHelp(activeChar, _command.substring(12));
			}
			else if (_command.startsWith("npc_"))
			{
				if (!activeChar.validateBypass(_command))
				{
					return;
				}
				int endOfId = _command.indexOf('_', 5);
				String id;
				if (endOfId > 0)
				{
					id = _command.substring(4, endOfId);
				}
				else
				{
					id = _command.substring(4);
				}
				try
				{
					L2Object object = L2World.getInstance().findObject(Integer.parseInt(id));
					if (_command.substring(endOfId + 1).startsWith("event_participate"))
					{
						L2Event.inscribePlayer(activeChar);
					}
					else if (_command.substring(endOfId + 1).startsWith("tvt_player_join "))
					{
						String teamName = _command.substring(endOfId + 1).substring(16);
						if (TvT._joining)
							TvT.addPlayer(activeChar, teamName);
						else
							activeChar.sendMessage("The event is already started. You can not join now!");
					}
					else if (_command.substring(endOfId + 1).startsWith("tvt_player_leave"))
					{
						if (TvT._joining)
							TvT.removePlayer(activeChar);
						else
							activeChar.sendMessage("The event is already started. You can not leave now!");
					}
					else if (_command.substring(endOfId + 1).startsWith("dmevent_player_join"))
					{
						if (DM._joining)
							DM.addPlayer(activeChar);
						else
							activeChar.sendMessage("The event is already started. You can not join now!");
					}
					else if (_command.substring(endOfId + 1).startsWith("dmevent_player_leave"))
					{
						if (DM._joining)
							DM.removePlayer(activeChar);
						else
							activeChar.sendMessage("The event is already started. You can not leave now!");
					}
					else if (_command.substring(endOfId + 1).startsWith("ctf_player_join "))
					{
						String teamName = _command.substring(endOfId + 1).substring(16);
						if (CTF._joining)
							CTF.addPlayer(activeChar, teamName);
						else
							activeChar.sendMessage("The event is already started. You can not join now!");
					}
					else if (_command.substring(endOfId + 1).startsWith("ctf_player_leave"))
					{
						if (CTF._joining)
							CTF.removePlayer(activeChar);
						else
							activeChar.sendMessage("The event is already started. You can not leave now!");
					}
                    else if (_command.substring(endOfId+1).startsWith("fos_player_join "))
                    {
                        String teamName = _command.substring(endOfId+1).substring(16);

                        if (FortressSiege._joining)
                        	FortressSiege.addPlayer(activeChar, teamName);
                        else
                            activeChar.sendMessage("The event has already begun. You can not join now!");
                    }

                    else if (_command.substring(endOfId+1).startsWith("fos_player_leave")){
                        if (FortressSiege._joining)
                        	FortressSiege.removePlayer(activeChar);
                        else
                            activeChar.sendMessage("The event has already begun. You can not withdraw your participation now!");
                    }
					if (Config.ALLOW_REMOTE_CLASS_MASTERS && object instanceof L2ClassMasterInstance || object != null && object instanceof L2NpcInstance && endOfId > 0 && activeChar.isInsideRadius(object, L2NpcInstance.INTERACTION_DISTANCE, false, false))
					{
						((L2NpcInstance) object).onBypassFeedback(activeChar, _command.substring(endOfId + 1));
					}
				}
				catch (NumberFormatException nfe)
				{
				}
			}
			// Draw a Symbol
			else if (_command.equals("menu_select?ask=-16&reply=1"))
			{
				L2Object object = activeChar.getTarget();
				if (object instanceof L2NpcInstance)
				{
					((L2NpcInstance) object).onBypassFeedback(activeChar, _command);
				}
			}
			else if (_command.equals("menu_select?ask=-16&reply=2"))
			{
				L2Object object = activeChar.getTarget();
				if (object instanceof L2NpcInstance)
				{
					((L2NpcInstance) object).onBypassFeedback(activeChar, _command);
				}
			}
			else if (_command.startsWith("manor_menu_select?"))
			{
				L2Object object = activeChar.getTarget();
				if (object instanceof L2NpcInstance)
				{
					((L2NpcInstance) object).onBypassFeedback(activeChar, _command);
				}
			}
			else if (_command.startsWith("bbs_"))
			{
				CommunityBoard.getInstance().handleCommands(getClient(), _command);
			}
			else if (_command.startsWith("_bbs"))
			{
				CommunityBoard.getInstance().handleCommands(getClient(), _command);
			}
			else if (_command.startsWith("Quest "))
			{
				if (!activeChar.validateBypass(_command))
				{
					return;
				}
				L2PcInstance player = getClient().getActiveChar();
				if (player == null)
				{
					return;
				}
				String p = _command.substring(6).trim();
				int idx = p.indexOf(' ');
				if (idx < 0)
				{
					player.processQuestEvent(p, "");
				}
				else
				{
					player.processQuestEvent(p.substring(0, idx), p.substring(idx).trim());
				}
			}
		}
		catch (Exception e)
		{
			_log.log(Level.WARNING, "Bad RequestBypassToServer: ", e);
		}
		// finally
		// {
		// activeChar.clearBypass();
		// }
	}

	/**
	 * @param client
	 */
	private void comeHere(L2PcInstance activeChar)
	{
		L2Object obj = activeChar.getTarget();
		if (obj == null)
		{
			return;
		}
		if (obj instanceof L2NpcInstance)
		{
			L2NpcInstance temp = (L2NpcInstance) obj;
			temp.setTarget(activeChar);
			temp.getAI().setIntention(CtrlIntention.AI_INTENTION_MOVE_TO, new L2CharPosition(activeChar.getX(), activeChar.getY(), activeChar.getZ(), 0));
			// temp.moveTo(player.getX(),player.getY(), player.getZ(), 0 );
		}
	}

	private void playerHelp(L2PcInstance activeChar, String path)
	{
		if (path.indexOf("..") != -1)
		{
			return;
		}
		String filename = "data/html/help/" + path;
		NpcHtmlMessage html = new NpcHtmlMessage(1);
		html.setFile(filename);
		activeChar.sendPacket(html);
	}

	/*
	 * (non-Javadoc)
	 * @see net.sf.l2j.gameserver.network.clientpackets.ClientBasePacket#getType()
	 */
	@Override
	public String getType()
	{
		return _C__21_REQUESTBYPASSTOSERVER;
	}
}
