/*
 * This file is part of the L2J Mobius project.
 * 
 * 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 handlers.effecthandlers;

import java.util.HashSet;
import java.util.Set;

import org.l2jmobius.commons.threads.ThreadPool;
import org.l2jmobius.commons.util.Rnd;
import org.l2jmobius.gameserver.ai.SummonAI;
import org.l2jmobius.gameserver.data.xml.SkillData;
import org.l2jmobius.gameserver.model.StatSet;
import org.l2jmobius.gameserver.model.actor.Creature;
import org.l2jmobius.gameserver.model.effects.AbstractEffect;
import org.l2jmobius.gameserver.model.holders.SkillHolder;
import org.l2jmobius.gameserver.model.item.instance.Item;
import org.l2jmobius.gameserver.model.skill.BuffInfo;
import org.l2jmobius.gameserver.model.skill.Skill;
import org.l2jmobius.gameserver.model.skill.SkillCaster;
import org.l2jmobius.gameserver.network.serverpackets.MagicSkillUse;

/**
 * Call Skill effect implementation.
 * @author NosBit
 */
public class CallSkill extends AbstractEffect
{
	private final SkillHolder _skill;
	private final int _skillLevelScaleTo;
	private final int _chance;
	
	private final Set<Integer> _targetCheckSkillIds = new HashSet<>();
	private final int _targetCheckSkillLevel;
	
	public CallSkill(StatSet params)
	{
		_skill = new SkillHolder(params.getInt("skillId"), params.getInt("skillLevel", 1), params.getInt("skillSubLevel", 0));
		_skillLevelScaleTo = params.getInt("skillLevelScaleTo", 0);
		_chance = params.getInt("chance", 100);
		for (String skill : params.getString("targetCheckSkillId", "").split(","))
		{
			if (!skill.isEmpty())
			{
				_targetCheckSkillIds.add(Integer.parseInt(skill));
			}
		}
		_targetCheckSkillLevel = params.getInt("targetCheckSkillLevel", 1);
	}
	
	@Override
	public boolean isInstant()
	{
		return true;
	}
	
	@Override
	public void instant(Creature effector, Creature effected, Skill skill, Item item)
	{
		if (!_targetCheckSkillIds.isEmpty())
		{
			for (Integer skillId : _targetCheckSkillIds)
			{
				final BuffInfo checkSkill = effected.getEffectList().getBuffInfoBySkillId(skillId);
				if ((checkSkill != null) && (_targetCheckSkillLevel >= checkSkill.getSkill().getLevel()))
				{
					return;
				}
			}
		}
		
		if ((_chance < 100) && (Rnd.get(100) > _chance))
		{
			return;
		}
		
		final Skill triggerSkill;
		if (_skillLevelScaleTo <= 0)
		{
			// Mobius: Use 0 to trigger max effector learned skill level.
			if (_skill.getSkillLevel() == 0)
			{
				final int knownLevel = effector.getSkillLevel(_skill.getSkillId());
				if (knownLevel > 0)
				{
					triggerSkill = SkillData.getInstance().getSkill(_skill.getSkillId(), knownLevel, _skill.getSkillSubLevel());
				}
				else
				{
					LOGGER.warning("Player " + effector + " called unknown skill " + _skill + " triggered by " + skill + " CallSkill.");
					return;
				}
			}
			else
			{
				triggerSkill = _skill.getSkill();
			}
		}
		else
		{
			final BuffInfo buffInfo = effected.getEffectList().getBuffInfoBySkillId(_skill.getSkillId());
			if (buffInfo != null)
			{
				triggerSkill = SkillData.getInstance().getSkill(_skill.getSkillId(), Math.min(_skillLevelScaleTo, buffInfo.getSkill().getLevel() + 1));
			}
			else
			{
				triggerSkill = _skill.getSkill();
			}
		}
		
		if (triggerSkill != null)
		{
			// Prevent infinite loop.
			if ((skill.getId() == triggerSkill.getId()) && (skill.getLevel() == triggerSkill.getLevel()))
			{
				return;
			}
			
			final int hitTime = triggerSkill.getHitTime();
			if (hitTime > 0)
			{
				if (effector.isSkillDisabled(triggerSkill))
				{
					return;
				}
				
				effector.broadcastPacket(new MagicSkillUse(effector, effected, triggerSkill.getDisplayId(), triggerSkill.getLevel(), hitTime, 0));
				if (effector.isSummon()) // Age of Magic: Call skill adjustment for summons.
				{
					effector.setTarget(null); // Stop attacking.
					ThreadPool.schedule(() ->
					{
						SkillCaster.triggerCast(effector, effected, triggerSkill);
						((SummonAI) effector.getAI()).defendAttack(effected); // Continue attacking.
					}, hitTime);
				}
				else
				{
					ThreadPool.schedule(() -> SkillCaster.triggerCast(effector, effected, triggerSkill), hitTime);
				}
			}
			else
			{
				SkillCaster.triggerCast(effector, effected, triggerSkill);
			}
		}
		else
		{
			LOGGER.warning("Skill not found effect called from " + skill);
		}
	}
}
