//::///////////////////////////////////////////////
//:: Spell Turning
//:: jx_sp_spellturn.nss
//:://////////////////////////////////////////////
/*
	Spells & Spell-like effects targeted on the Spell
	Turning protected creature are turned back upon
	the original caster (except area spells & touch
	ranged spells).
	1d4 + 6 spell levels are affected by Spell Turning,
	then the protection disapears.
*/
//:://////////////////////////////////////////////
//:: Created By: jallaix
//:: Created On: Mar 7, 2007
//:: Updated On: Mar 13, 2007
//:://////////////////////////////////////////////
// jallaix 03/12/07 - replaced the == operator by the & operator to compare metamagic features
// jallaix 03/12/07 - corrected a bug when the spell was already applied


#include "x2_inc_spellhook"


void mainSpell();
void main()
{
	AssignCommand(JXGetCaster(), mainSpell());
}

void mainSpell()
{
    if (!X2PreSpellCastCode())
    {
        JXPostSpellCastCode();
		return;
    }

	object oCaster = OBJECT_SELF;

	// Remove the current Spell Turning effect if it exists
	if (GetHasSpellEffect(SPELL_SPELL_TURNING, oCaster))
	{
		DeleteLocalInt(oCaster, "JX_SP_SPELLTURN_LVLS");
		effect eLoop = GetFirstEffect(oCaster);
		while (GetIsEffectValid(eLoop))
		{
			if (GetEffectSpellId(eLoop) == SPELL_SPELL_TURNING)
			{
				RemoveEffect(oCaster, eLoop);
			}
			eLoop = GetNextEffect(oCaster);
		}
	}

	// Get the duration and number of level to absorb
	int iMetaMagic = JXGetMetaMagicFeat();
    float fDuration = TurnsToSeconds(JXGetCasterLevel(oCaster));
	int iNumberLevels = 6 + d4();
	if (iMetaMagic & METAMAGIC_EXTEND)
		fDuration = fDuration * 2;
	if (iMetaMagic & METAMAGIC_MAXIMIZE)
		iNumberLevels = 10;
	if (iMetaMagic & METAMAGIC_EMPOWER)
		iNumberLevels = iNumberLevels + iNumberLevels / 2;

	// Create the effect
    effect eDur = EffectVisualEffect(VFX_DUR_SPELL_SPELL_MANTLE);
	effect eAbsorb = EffectSpellLevelAbsorption(-1, 0);
	effect eLink = EffectLinkEffects(eDur, eAbsorb);
	JXApplyEffectToObject(DURATION_TYPE_TEMPORARY, eLink, oCaster, fDuration);

	// Set the number of spell absorption levels
	SetLocalInt(oCaster, "JX_SP_SPELLTURN_LVLS", iNumberLevels);
	DelayCommand(fDuration, DeleteLocalInt(oCaster, "JX_SP_SPELLTURN_LVLS"));
}