/*
 * 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 l2.universe.scripts.hellbound;

import javolution.util.FastList;
import l2.universe.gameserver.ai.CtrlIntention;
import l2.universe.gameserver.instancemanager.InstanceManager;
import l2.universe.gameserver.instancemanager.InstanceManager.InstanceWorld;
import l2.universe.gameserver.instancemanager.HellboundManager;
import l2.universe.gameserver.model.L2Party;
import l2.universe.gameserver.model.actor.L2Npc;
import l2.universe.gameserver.model.actor.instance.L2PcInstance;
import l2.universe.gameserver.model.quest.Quest;
import l2.universe.gameserver.network.SystemMessageId;
import l2.universe.gameserver.network.serverpackets.CreatureSay;
import l2.universe.gameserver.network.serverpackets.SystemMessage;
import l2.universe.gameserver.util.Util;
import l2.universe.util.Rnd;


public class MarketTown extends Quest
{
	private static final String qn = "MarketTown";

	// NPCs
	private static final int KANAF = 32346;
	private static final int PRISONER = 32358;
	
	// Mobs
	private static final int AMASKARI = 22449;
	private static final int KEYMASTER = 22361;
	
	private static final int TOWN_GUARD = 22359;
	private static final int TOWN_PATROLMAN = 22360;
	
	private static final int[] TOWN_MOBS = { TOWN_GUARD, TOWN_PATROLMAN };

	private static final int[][] KLOCS = {
		{14264, 250333, -1935, 15133},
		{19961, 256249, -2086, 47344},
		{17271, 252888, -2010, 64381},
		{15784, 252413, -2010, 49254},
		{22029, 254160, -2005, 60246}
	};

	private teleCoord tele;
	private FastList<L2Npc> _slaves;
	private static int trustp = 0;
	private boolean Lock = false;

	public class MTWorld extends InstanceWorld
	{
		public MTWorld()
		{
			InstanceManager.getInstance();
		}
	}
	
	private class teleCoord
	{
		boolean isInstance;
		int instanceId;
		int x;
		int y;
		int z;
	}
	
	private boolean checkConditions(L2PcInstance player)
	{
		L2Party party = player.getParty();
		if (party == null)
		{
			player.sendPacket(SystemMessage.getSystemMessage(2101));
			return false;
		}
		if (party.getLeader() != player)
		{
			player.sendPacket(SystemMessage.getSystemMessage(2185));
			return false;
		}
		for (L2PcInstance partyMember : party.getPartyMembers())
		{
			if (partyMember.getLevel() < 78)
			{
				SystemMessage sm = SystemMessage.getSystemMessage(2097);
				sm.addPcName(partyMember);
				party.broadcastToPartyMembers(sm);
				return false;
			}
			if (!Util.checkIfInRange(1000, player, partyMember, true))
			{
				SystemMessage sm = SystemMessage.getSystemMessage(2096);
				sm.addPcName(partyMember);
				party.broadcastToPartyMembers(sm);
				return false;
			}
		}
		return true;
		
	}
	
	private void teleportplayer(L2PcInstance player, teleCoord teleto)
	{
		player.getAI().setIntention(CtrlIntention.AI_INTENTION_IDLE);
		player.setInstanceId(teleto.instanceId);
		player.teleToLocation(teleto.x, teleto.y, teleto.z);
		return;
	}

	protected int enterInstance(L2PcInstance player)
	{
		int instanceId = 0;
		//check for existing instances for this player
		InstanceWorld world = InstanceManager.getInstance().getPlayerWorld(player);
		//existing instance
		if (world != null)
		{
			if (!(world instanceof MTWorld))
			{
				player.sendPacket(SystemMessage.getSystemMessage(SystemMessageId.ALREADY_ENTERED_ANOTHER_INSTANCE_CANT_ENTER));
				return 0;
			}

			if (tele.isInstance)
				teleportplayer(player, tele);
		}
		//New instance
		else
		{
			if (!checkConditions(player))
				return 0;
			L2Party party = player.getParty();
			instanceId = InstanceManager.getInstance().createDynamicInstance("HBTown.xml");
			world = new MTWorld();
			world.instanceId = instanceId;
			world.templateId = instanceId;
			world.status = 0;
			InstanceManager.getInstance().addWorld(world);
			_log.info("HellboundTown started Instance: " + instanceId + " created by player: " + player.getName());
			int[] loc = KLOCS[Rnd.get(KLOCS.length)];
			tele.x = 13881;
			tele.y = 255491;
			tele.z = -2025;
			tele.instanceId = world.instanceId;
			tele.isInstance = true;
			addSpawn(KEYMASTER, loc[0], loc[1], loc[2], loc[3], false, 0, false, world.instanceId);
			for (L2PcInstance partyMember : party.getPartyMembers())
			{
				teleportplayer(partyMember, tele);
				world.allowed.add(partyMember.getObjectId());
			}
		}
		
		return instanceId;
	}

	@Override
	public String onAdvEvent(String event, L2Npc npc, L2PcInstance player)
	{
		if (event.equalsIgnoreCase("check_trust_p"))
		{
			if (trustp < 500000)
				return null;

			HellboundManager.getInstance().changeLevel(11);
		    trustp = 0;
		    saveGlobalQuestVar("trust10p", Integer.toString(trustp));
		    cancelQuestTimers("check_trust_p");
		}

		return super.onAdvEvent(event, npc, player);
	}
	
	@Override
	public String onAttack(L2Npc npc, L2PcInstance attacker, int damage, boolean isPet)
	{
		int npcId = npc.getNpcId();
		if (npcId == AMASKARI)
		{
			double maxHp = npc.getMaxHp();
			double nowHp = npc.getStatus().getCurrentHp();
			int objId = npc.getObjectId();
		    if (nowHp < maxHp * 0.1 && !Lock)
		    {
				npc.broadcastPacket(new CreatureSay(objId, 0, npc.getName(), "I will make everyone feel the same suffering as me!"));
				Lock = true;
		    }
		}

		return super.onAttack(npc, attacker, damage, isPet);
	}
	
	@Override
	public String onFirstTalk(L2Npc npc, L2PcInstance player)
	{
		if (HellboundManager.getInstance().getLevel() < 10) 
			return "<html><body>How did you get inward? The gate of lock is closed... A patrol can appear at any moment. Run!</body></html>";
		
		npc.showChatWindow(player);

		return super.onFirstTalk(npc, player);
	}
	
	@Override
	public String onKill(L2Npc npc, L2PcInstance killer, boolean isPet)
	{
	    int npcId = npc.getNpcId();
	    if (npcId == KEYMASTER)
	    {
		    addSpawn(AMASKARI, 19347, 253103, -2019, 41941, false, 0, false, npc.getInstanceId());
		    HellboundManager.getInstance().increaseTrust(250);
		    trustp += 250;
		    saveGlobalQuestVar("trust10p", Integer.toString(trustp));
	    }
	    else if (npcId == AMASKARI)
	    {
		    HellboundManager.getInstance().increaseTrust(500);
		    trustp += 500;
		    saveGlobalQuestVar("trust10p", Integer.toString(trustp));
		    
		    if (_slaves.isEmpty())
		    	return null;
		    
			for (L2Npc i : _slaves)
			{
				  i.setIsInvul(true);
				  i.broadcastPacket(new CreatureSay(i.getObjectId(), 0, i.getName(), "Thank you for saving me!"));
				  i.decayMe();
			}
			
			_slaves.clear();
	    }
	    else if (npcId == PRISONER)
	    {
		    HellboundManager.getInstance().increaseTrust(-10);
		    trustp -= 10;
		    saveGlobalQuestVar("trust10p", Integer.toString(trustp));
	    }
		else if (TOWN_MOBS.equals(npcId))
		{
			HellboundManager.getInstance().increaseTrust(20);
		    trustp += 20;
		    saveGlobalQuestVar("trust10p", Integer.toString(trustp));
		}

		return super.onKill(npc, killer, isPet);
	}
	
	@Override
	public String onSpawn(L2Npc npc)
	{
	    int npcId = npc.getNpcId();
	    
	    if (npcId == AMASKARI)
	    {
		    int xx = npc.getX();
		    int yy = npc.getY();
		    int zz = npc.getZ();
		    
		    for (int i = 0; i < 9; i++)
		    {
			    int offsetX = xx + (50 - Rnd.get(250));
			    int offsetY = yy + (50 - Rnd.get(250));
			    L2Npc newSlave = addSpawn(22450, offsetX, offsetY, zz, 0, false, 0, false, npc.getInstanceId());
			    newSlave.setRunning();
			    newSlave.getAI().setIntention(CtrlIntention.AI_INTENTION_FOLLOW, npc);
			    _slaves.add(newSlave);
		    }
	    }
		return super.onSpawn(npc);
	}
	
	@Override
	public String onTalk(L2Npc npc, L2PcInstance talker)
	{
		int hellboundLevel = HellboundManager.getInstance().getLevel();
		if (hellboundLevel < 10) 
			return "<html><body>Who are you?...<br>Go away from here, I do not want to talk with you!</body></html>";
		
		int npcId = npc.getNpcId();
		if (npcId == KANAF)
		{
			if (!checkConditions(talker))
				return null;
			
			enterInstance(talker);
		}
		else if (npcId == PRISONER)
		{
		    String htmltext = "<html><body>Native Prisoner:<br>An exempt Native Prisoner hardly regains consciousness. Till to dash to hurry, he tries to express you the gratitude.</body></html>";
			npc.decayMe();
			if (hellboundLevel == 10)
			{
				npc.deleteMe();
			    HellboundManager.getInstance().increaseTrust(50);
			    trustp += 50;
				saveGlobalQuestVar("trust10p", Integer.toString(trustp));
			}
			
			return htmltext;
		}

		return super.onTalk(npc, talker);
	}
	
	public MarketTown(int questId, String name, String descr)
	{
		super(questId, name, descr);
		tele = new teleCoord();
		_slaves = new FastList<L2Npc>();
		try { trustp = Integer.parseInt(loadGlobalQuestVar("trust10p")); }
		catch (NumberFormatException ex) {}
		saveGlobalQuestVar("trust10p", Integer.toString(trustp));
		if (HellboundManager.getInstance().getLevel() == 10) 
			startQuestTimer("check_trust_p", 60000, null, null, true);
		
		addSpawnId(AMASKARI);
		addAttackId(AMASKARI);
		addKillId(AMASKARI);
		addFirstTalkId(KANAF);
		addStartNpc(KANAF);
		addTalkId(KANAF);
		addKillId(KEYMASTER);
		addTalkId(PRISONER);
		for ( int i : TOWN_MOBS)
		    addKillId(i);
	}
	
	/**
	 * @param args
	 */
	public static void main(String[] args)
	{
		new MarketTown(-1, qn, "hellbound");
	}
}
