/*
 * Copyright (C) 2004-2014 L2J DataPack
 * 
 * This file is part of L2J DataPack.
 * 
 * L2J DataPack 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.
 * 
 * L2J DataPack 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 ai.group_template;

import static com.l2jserver.gameserver.datatables.SkillData.*;
import ai.npc.AbstractNpcAI;

import com.l2jserver.gameserver.GeoData;
import com.l2jserver.gameserver.ai.CtrlIntention;
import com.l2jserver.gameserver.datatables.SpawnTable;
import com.l2jserver.gameserver.handler.IItemHandler;
import com.l2jserver.gameserver.handler.ItemHandler;
import com.l2jserver.gameserver.model.L2Spawn;
import com.l2jserver.gameserver.model.Location;
import com.l2jserver.gameserver.model.actor.L2Attackable;
import com.l2jserver.gameserver.model.actor.L2Character;
import com.l2jserver.gameserver.model.actor.L2Npc;
import com.l2jserver.gameserver.model.actor.L2Playable;
import com.l2jserver.gameserver.model.actor.instance.L2PcInstance;
import com.l2jserver.gameserver.model.holders.SkillHolder;
import com.l2jserver.gameserver.model.items.instance.L2ItemInstance;
import com.l2jserver.gameserver.model.skills.Skill;
import com.l2jserver.gameserver.network.NpcStringId;
import com.l2jserver.gameserver.network.clientpackets.Say2;
import com.l2jserver.gameserver.util.Util;

/**
 * Primeval Isle AI.
 * @author St3eT
 */
public final class PrimevalIsle extends AbstractNpcAI
{
	// NPC
	private static final int EGG = 18344; // Ancient Egg
	private static final int SAILREN = 29065; // Sailren
	private static final int ORNIT = 22742; // Ornithomimus
	private static final int DEINO = 22743; // Deinonychus
	private static final int[] SPRIGNANT =
	{
		18345, // Sprigant (Anesthesia)
		18346, // Sprigant (Deadly Poison)
	};
	private static final int[] MONSTERS =
	{
		22196, // Velociraptor
		22198, // Velociraptor
		22200, // Ornithomimus
		22202, // Ornithomimus
		22203, // Deinonychus
		22205, // Deinonychus
		22208, // Pachycephalosaurus
		22210, // Pachycephalosaurus
		22211, // Wild Strider
		22213, // Wild Strider
		22223, // Velociraptor
		22224, // Ornithomimus
		22225, // Deinonychus
		22226, // Pachycephalosaurus
		22227, // Wild Strider
		ORNIT, // Ornithomimus
		DEINO, // Deinonychus
	};
	private static final int[] TREX =
	{
		22215, // Tyrannosaurus
		22216, // Tyrannosaurus
		22217, // Tyrannosaurus
	};
	private static final int[] VEGETABLE =
	{
		22200, // Ornithomimus
		22201, // Ornithomimus
		22202, // Ornithomimus
		22203, // Deinonychus
		22204, // Deinonychus
		22205, // Deinonychus
		22224, // Ornithomimus
		22225, // Deinonychus
	};
	// Item
	private static final int DEINONYCHUS = 14828; // Deinonychus Mesozoic Stone
	// Skill
	private static final int ANESTHESIA = getSkillHashCode(5085, 1); // Anesthesia
	private static final int DEADLY_POISON = getSkillHashCode(5086, 1); // Deadly Poison
	private static final int SELFBUFF1 = getSkillHashCode(5087, 1); // Berserk
	private static final int SELFBUFF2 = getSkillHashCode(5087, 2); // Berserk
	private static final int LONGRANGEDMAGIC1 = getSkillHashCode(5120, 1); // Stun
	private static final int PHYSICALSPECIAL1 = getSkillHashCode(5083, 4); // Stun
	private static final int PHYSICALSPECIAL2 = getSkillHashCode(5081, 4); // Silence
	private static final int PHYSICALSPECIAL3 = getSkillHashCode(5082, 4); // NPC Spinning, Slashing Trick
	private static final int CREW_SKILL = getSkillHashCode(6172, 1); // Presentation - Tyranno
	private static final int INVIN_BUFF_ON = getSkillHashCode(5225, 1); // Invincible
	
	private PrimevalIsle()
	{
		super(PrimevalIsle.class.getSimpleName(), "ai/group_template");
		addSpawnId(TREX);
		addSpawnId(SPRIGNANT);
		addSpawnId(MONSTERS);
		addAggroRangeEnterId(TREX);
		addSpellFinishedId(TREX);
		addAttackId(EGG);
		addAttackId(TREX);
		addAttackId(MONSTERS);
		addKillId(EGG, SAILREN, DEINO, ORNIT);
		addSeeCreatureId(TREX);
		addSeeCreatureId(MONSTERS);
		addMoveFinishedId(TREX);		//+[JOJO]
		//addMoveFinishedId(SPRIGNANT);	//+[JOJO]
		addMoveFinishedId(MONSTERS);	//+[JOJO]
		
if (!com.l2jserver.Config.FIX_onSpawn_for_SpawnTable) {{
		for (int npcId : SPRIGNANT)
		{
			for (L2Spawn spawn : SpawnTable.getInstance().getSpawns(npcId))
			{
				onSpawn(spawn.getLastSpawn());
			}
		}
		
		for (int npcId : TREX)
		{
			for (L2Spawn spawn : SpawnTable.getInstance().getSpawns(npcId))
			{
				onSpawn(spawn.getLastSpawn());
			}
		}
}}
	}
	
	@Override
	public String onSpellFinished(L2Npc npc, L2PcInstance player, Skill skill)
	{
		// TREX[]
		if (skill.getId() == getSkillId(CREW_SKILL))
		{
			startQuestTimer("START_INVUL", 4000, npc, null);
			final L2Npc target = (L2Npc) npc.getTarget();
			if (target != null)
			{
				target.doDie(npc);
			}
		}
		if (npc.isInCombat())
		{
			final L2Attackable mob = (L2Attackable) npc;
			final L2Character target = mob.getMostHated();
			if (npc.getCurrentHp() / npc.getMaxHp() * 100 < 30)
			{
				if (skill.getId() == getSkillId(SELFBUFF1))
				{
					npc.setScriptValue(1);/*次回のonAttackでdoCast(SELFBUFF2)*/
					if (target != null)
					{
						npc.setTarget(target);
						mob.setIsRunning(true);
						mob.addDamageHate(target, 0, 555);
						mob.getAI().setIntention(CtrlIntention.AI_INTENTION_ATTACK, target);
					}
				}
				else if (skill.getId() == getSkillId(SELFBUFF2))
				{
					npc.setScriptValue(5);
					if (target != null)
					{
						npc.setTarget(target);
						mob.setIsRunning(true);
						mob.addDamageHate(target, 0, 555);
						mob.getAI().setIntention(CtrlIntention.AI_INTENTION_ATTACK, target);
					}
				}
			}
			else if (npc.getCurrentHp() / npc.getMaxHp() * 100 < 60)
			{
				if (skill.getId() == getSkillId(SELFBUFF1))
				{
					npc.setScriptValue(3);
					if (target != null)
					{
						npc.setTarget(target);
						mob.setIsRunning(true);
						mob.addDamageHate(target, 0, 555);
						mob.getAI().setIntention(CtrlIntention.AI_INTENTION_ATTACK, target);
					}
				}
			}
		}
		return super.onSpellFinished(npc, player, skill);
	}
	
	@Override
	public String onAdvEvent(String event, L2Npc npc, L2PcInstance player)
	{
		switch (event)
		{
			case "USE_SKILL":	// onSpawn SPRIGNANT[]
			{
				if (npc.isVisible() && !npc.isDead())
				{
					if (npc.hasAI())
						npc.doCast((npc.getId() == SPRIGNANT[0] ? getSkill(ANESTHESIA) : getSkill(DEADLY_POISON)));
					startQuestTimer("USE_SKILL", 15000, npc, null);
				}
				break;
			}
			case "GHOST_DESPAWN":	// onSpawn TREX[]
			{
				if (npc.isVisible() && !npc.isDead())
				{
					if (!npc.isInCombat())
					{
						npc.deleteMe();
					}
					else
					{
						startQuestTimer("GHOST_DESPAWN", 1800000, npc, null);
					}
				}
				break;
			}
			case "TREX_ATTACK":	// onAggroRangeEnter TREX[]
			{
				if (npc.isVisible() && !npc.isDead() && !player.isDead())
				{
					npc.setScriptValue(0);
					if (player.isInsideRadius(npc, 800, true, false))
					{
						npc.setTarget(player);
						npc.doCast(getSkill(LONGRANGEDMAGIC1));
						attackPlayer((L2Attackable) npc, player);
					}
				}
				break;
			}
			case "START_INVUL":	// onSpellFinished TREX[]
			{
				if (npc.isVisible() && !npc.isDead())
				{
					npc.doCast(getSkill(INVIN_BUFF_ON));
					startQuestTimer("START_INVUL_2", 30000, npc, null);
				}
				break;
			}
			case "START_INVUL_2":	// TREX[]
			{
				if (npc.isVisible() && !npc.isDead())
				{
					getSkill(INVIN_BUFF_ON).applyEffects(npc, npc);
				}
				break;
			}
		}
		return super.onAdvEvent(event, npc, player);
	}
	
	@Override
	public String onSeeCreature(L2Npc npc, L2Character creature, boolean isSummon)
	{
		if (Util.contains(MONSTERS, npc.getId()))	// MONSTERS[] see player
		{
			if (creature.isPlayer())
			{
				final int ag_type = npc.getTemplate().getParameters().getInt("ag_type", 0);
				
			//	if (((getRandom(100) < 30) && (npc.getId() == DEINO)) || ((npc.getId() == ORNIT) && npc.isScriptValue(0)))	// 元(svn.l2jdp.com r10100)
			//	if (getRandom(100) < 30 && npc.getId() == DEINO || npc.getId() == ORNIT && npc.isScriptValue(0))			// 余分の括弧の除去
			//	if (getRandom(100) < 30 && (npc.getId() == DEINO || npc.getId() == ORNIT) && npc.isScriptValue(0))			// もしかしてコレ？
				if ((npc.getId() == DEINO || npc.getId() == ORNIT) && npc.getAI().getIntention() == CtrlIntention.AI_INTENTION_ACTIVE && getRandom(100) < 30)	//+[JOJO]
				{
					final L2Attackable mob = (L2Attackable) npc;
					mob.clearAggroList();
					npc.setScriptValue(1);
					npc.setRunning();
					
					final int distance = 3000;
					final double angle = Math.atan2(npc.getY() - creature.getY(), npc.getX() - creature.getX());
					final int newX = (int) (npc.getX() + Math.cos(angle) * distance);
					final int newY = (int) (npc.getY() + Math.sin(angle) * distance);
					final Location loc = GeoData.getInstance().moveCheck(npc.getX(), npc.getY(), npc.getZ(), newX, newY, npc.getZ(), npc.getInstanceId());
					npc.getAI().setIntention(CtrlIntention.AI_INTENTION_MOVE_TO, loc, 0);
				}
				else if (ag_type == 1)
				{
					final int probPhysicalSpecial1 = npc.getTemplate().getParameters().getInt("ProbPhysicalSpecial1", 0);
					final int probPhysicalSpecial2 = npc.getTemplate().getParameters().getInt("ProbPhysicalSpecial2", 0);
					final int SKILL_MULTIPLIER = npc.getVariables().getInt("SKILL_MULTIPLIER");
					if (getRandom(100) <= probPhysicalSpecial1 * SKILL_MULTIPLIER)
					{
						final SkillHolder physicalSpecial1 = npc.getTemplate().getParameters().getObject("PhysicalSpecial1", SkillHolder.class);
						if (!npc.isSkillDisabled(physicalSpecial1.getSkill()))
						{
							npc.setTarget(creature);
							npc.doCast(physicalSpecial1.getSkill());
						}
					}
					else if (getRandom(100) <= probPhysicalSpecial2 * SKILL_MULTIPLIER)
					{
						final SkillHolder physicalSpecial2 = npc.getTemplate().getParameters().getObject("PhysicalSpecial2", SkillHolder.class);
						if (!npc.isSkillDisabled(physicalSpecial2.getSkill()))
						{
							npc.setTarget(creature);
							npc.doCast(physicalSpecial2.getSkill());
						}
					}
				}
			}
		}
		else if (Util.contains(VEGETABLE, creature.getId()))	// TREX[] see VEGETABLE[]
		{
			npc.setTarget(creature);
			npc.doCast(getSkill(CREW_SKILL));
			npc.setIsRunning(true);
			npc.getAI().setIntention(CtrlIntention.AI_INTENTION_ATTACK, creature);
		}
		return super.onSeeCreature(npc, creature, isSummon);
	}
	
	@Override
	public String onAggroRangeEnter(L2Npc npc, L2PcInstance player, boolean isSummon)
	{
		// TREX[]
		if (npc.isScriptValue(0))
		{
			npc.setScriptValue(1);
			broadcastNpcSay(npc, Say2.NPC_ALL, "?");
			((L2Attackable) npc).clearAggroList();
			startQuestTimer("TREX_ATTACK", 6000, npc, player);
		}
		return super.onAggroRangeEnter(npc, player, isSummon);
	}
	
	@Override
	public String onAttack(L2Npc npc, L2PcInstance attacker, int damage, boolean isSummon)
	{
		if (npc.getId() == EGG)
		{
			if (getRandom(100) <= 80 && npc.isScriptValue(0))
			{
				npc.setScriptValue(1);
				final L2Playable playable = isSummon ? attacker.getSummon() : attacker;
				for (L2Character characters : npc.getKnownList().getKnownCharactersInRadius(500))
				{
					if (characters != null && characters.isAttackable() && getRandomBoolean())
					{
						L2Attackable monster = (L2Attackable) characters;
						attackPlayer(monster, playable);
					}
				}
			}
		}
		else if (Util.contains(TREX, npc.getId()))
		{
			final L2Attackable mob = (L2Attackable) npc;
			final L2Character target = mob.getMostHated();
			
			if (npc.getCurrentHp() / npc.getMaxHp() * 100 < 30)
			{
				if (npc.isScriptValue(3))
				{
					if (!npc.isSkillDisabled(getSkill(SELFBUFF1)))
					{
						npc.doCast(getSkill(SELFBUFF1));
					}
				}
				else if (npc.isScriptValue(1))
				{
					if (!npc.isSkillDisabled(getSkill(SELFBUFF2)))
					{
						npc.doCast(getSkill(SELFBUFF2));
					}
				}
			}
			else if (npc.getCurrentHp() / npc.getMaxHp() * 100 < 60)
			{
				if (npc.isScriptValue(3))
				{
					if (!npc.isSkillDisabled(getSkill(SELFBUFF1)))
					{
						npc.doCast(getSkill(SELFBUFF1));
					}
				}
			}
			
			if (Util.calculateDistance(npc, attacker, true, false) > 100)
			{
				if (!npc.isSkillDisabled(getSkill(LONGRANGEDMAGIC1)) && getRandom(100) <= 10 * npc.getScriptValue())
				{
					npc.setTarget(attacker);
					npc.doCast(getSkill(LONGRANGEDMAGIC1));
				}
			}
			else
			{
				if (!npc.isSkillDisabled(getSkill(LONGRANGEDMAGIC1)) && getRandom(100) <= 10 * npc.getScriptValue())
				{
					npc.setTarget(target);
					npc.doCast(getSkill(LONGRANGEDMAGIC1));
				}
				if (!npc.isSkillDisabled(getSkill(PHYSICALSPECIAL1)) && getRandom(100) <= 5 * npc.getScriptValue())
				{
					npc.setTarget(target);
					npc.doCast(getSkill(PHYSICALSPECIAL1));
				}
				if (!npc.isSkillDisabled(getSkill(PHYSICALSPECIAL2)) && getRandom(100) <= 3 * npc.getScriptValue())
				{
					npc.setTarget(target);
					npc.doCast(getSkill(PHYSICALSPECIAL2));
				}
				if (!npc.isSkillDisabled(getSkill(PHYSICALSPECIAL3)) && getRandom(100) <= 5 * npc.getScriptValue())
				{
					npc.setTarget(target);
					npc.doCast(getSkill(PHYSICALSPECIAL3));
				}
			}
		}
		else // MONSTERS[]
		{
			L2Character target = null;
			
			if (npc.getCurrentHp() / npc.getMaxHp() * 100 <= 50)
			{
				npc.getVariables().set("SKILL_MULTIPLIER", 2);
			}
			else
			{
				npc.getVariables().set("SKILL_MULTIPLIER", 1);
			}
			
			if (npc.getCurrentHp() / npc.getMaxHp() * 100 <= 30 && npc.getVariables().getInt("SELFBUFF_USED") == 0)
			{
				final L2Attackable mob = (L2Attackable) npc;
				target = mob.getMostHated();
				mob.clearAggroList();
				final SkillHolder selfRangeBuff1 = npc.getTemplate().getParameters().getObject("SelfRangeBuff1", SkillHolder.class);
				if (!npc.isSkillDisabled(selfRangeBuff1.getSkill()))
				{
					npc.getVariables().set("SELFBUFF_USED", 1);
					npc.doCast(selfRangeBuff1.getSkill());
					npc.setIsRunning(true);
					npc.getAI().setIntention(CtrlIntention.AI_INTENTION_ATTACK, target);
				}
			}
			
			if (target != null)
			{
				final int probPhysicalSpecial1 = npc.getTemplate().getParameters().getInt("ProbPhysicalSpecial1", 0);
				final int probPhysicalSpecial2 = npc.getTemplate().getParameters().getInt("ProbPhysicalSpecial2", 0);
				final int SKILL_MULTIPLIER = npc.getVariables().getInt("SKILL_MULTIPLIER");
				if (getRandom(100) <= probPhysicalSpecial1 * SKILL_MULTIPLIER)
				{
					final SkillHolder physicalSpecial1 = npc.getTemplate().getParameters().getObject("PhysicalSpecial1", SkillHolder.class);
					if (!npc.isSkillDisabled(physicalSpecial1.getSkill()))
					{
						npc.setTarget(target);
						npc.doCast(physicalSpecial1.getSkill());
					}
				}
				if (getRandom(100) <= probPhysicalSpecial2 * SKILL_MULTIPLIER)
				{
					final SkillHolder physicalSpecial2 = npc.getTemplate().getParameters().getObject("PhysicalSpecial2", SkillHolder.class);
					if (!npc.isSkillDisabled(physicalSpecial2.getSkill()))
					{
						npc.setTarget(target);
						npc.doCast(physicalSpecial2.getSkill());
					}
				}
			}
		}
		return super.onAttack(npc, attacker, damage, isSummon);
	}
	
	@Override
	public String onKill(L2Npc npc, L2PcInstance killer, boolean isSummon)
	{
		// EGG, SAILREN, DEINO, ORNIT
		if ((npc.getId() == DEINO || npc.getId() == ORNIT) && !npc.isScriptValue(1))
		{
			return super.onKill(npc, killer, isSummon);
		}
		if (npc.getId() == SAILREN || getRandom(100) < 3)
		{
			final L2PcInstance player = npc.getId() == SAILREN ? getRandomPartyMember(killer) : killer;
			if (player.getInventory().getSize(false) <= player.getInventoryLimit() * 0.8)
			{
				giveItems(player, DEINONYCHUS, 1);
				final L2ItemInstance summonItem = player.getInventory().getItemByItemId(DEINONYCHUS);
				final IItemHandler handler = ItemHandler.getInstance().getHandler(summonItem.getEtcItem());
				if (handler != null && !player.hasPet())
				{
					handler.useItem(player, summonItem, true);
				}
				showOnScreenMsg(player, NpcStringId.LIFE_STONE_FROM_THE_BEGINNING_ACQUIRED, 2, 6000);
			}
			else
			{
				showOnScreenMsg(player, NpcStringId.WHEN_INVENTORY_WEIGHT_NUMBER_ARE_MORE_THAN_80_THE_LIFE_STONE_FROM_THE_BEGINNING_CANNOT_BE_ACQUIRED, 2, 6000);
			}
		}
		return super.onKill(npc, killer, isSummon);
	}
	
	@Override
	public String onSpawn(L2Npc npc)
	{
		if (Util.contains(SPRIGNANT, npc.getId()))
		{
			startQuestTimer("USE_SKILL", 15000, npc, null);
		}
		else if (Util.contains(TREX, npc.getId()))
		{
			final int collectGhost = npc.getTemplate().getParameters().getInt("CollectGhost", 0);
			final int collectDespawn = npc.getTemplate().getParameters().getInt("CollectGhostDespawnTime", 30);
			
			if (collectGhost == 1)
			{
				startQuestTimer("GHOST_DESPAWN", collectDespawn * 60000, npc, null);
			}
		}
		else // MONSTERS[]
		{
			npc.getVariables().set("SELFBUFF_USED", 0);
			npc.getVariables().set("SKILL_MULTIPLIER", 1);
		}
		return super.onSpawn(npc);
	}
	
	@Override
	public boolean onMoveFinished(L2Npc npc)
	{
		// TREX[], MONSTERS[]
		L2Spawn spawn = npc.getSpawn();
		//if (Math.hypot(npc.getX() - spawn.getX(), npc.getY() - spawn.getY()) < 50)
		if (spawn == null) {
		}
		else if (npc.getX() == spawn.getX() && npc.getY() == spawn.getY())
		{
			npc.getVariables().remove("SCRIPT_VAL"); // npc.setScriptValue(0) TREX[], MONSTERS[]
			if (Util.contains(MONSTERS, npc.getId()))
			{
				npc.getVariables().set("SELFBUFF_USED", 0);
				npc.getVariables().set("SKILL_MULTIPLIER", 1);
			}
		}
		return super.onMoveFinished(npc);
	}
	
	public static void main(String[] args)
	{
		new PrimevalIsle();
	}
}