/* This is the OnHeartbeat script for the Hatchling object from
 * the Deck of Hazards. It summons a hatchling that follows the
 * caster around. The object is destroyed when the hatchling is
 * transformed into an ancient dragon (good for one fight).
 */

#include "x0_i0_deckmany"

void main()
{
	//SendMessageToPC(GetFirstPC(),"hatch heart fired");

    // Get the stored target
    object oTarget = GetLocalObject(OBJECT_SELF, "X0_DECK_TARGET");
    if (!GetIsObjectValid(oTarget))
        return;

    // Get the stored hatchling
	
	
	object oHatch = GetLocalObject(oTarget, "X0_DECK_HATCH");
	object oRedDragon = GetLocalObject(oTarget,"oRedDragon");
	
	int nIsHatchFighting = GetIsInCombat(oHatch);
	int nIsAdultFighting = GetIsInCombat(oRedDragon);
	int nAdultDragonOut = GetLocalInt(oTarget,"nAdultDragonOut");
	
	//SendMessageToPC(GetFirstPC(),"Adult dragon name = " + GetName(oRedDragon));
	//SendMessageToPC(GetFirstPC(),"Adult dragon out? = " + IntToString(nAdultDragonOut));
	//SendMessageToPC(GetFirstPC(),"Adult dragon figthing? = " + IntToString(nIsAdultFighting));
	
    
    if (GetIsObjectValid(oHatch) && nIsHatchFighting != TRUE && nAdultDragonOut == 0  ) {
        // hatchling is still around
        return;
    }
	else if(GetIsObjectValid(oHatch) && nIsHatchFighting == TRUE && nAdultDragonOut == 0)
	{
		 // hatchling is fighting, bring out Momma!
		 	SetLocalInt(oTarget,"nAdultDragonOut",1);
		 	RemoveSummonedAssociate(oTarget,oHatch);
		      DestroyObject(oHatch,0.0);	
		      effect eSummon = EffectSummonCreature("c_reddragon",
                                          VFX_IMP_DIVINE_STRIKE_HOLY,
                                          0.0,1);

                /*ApplyEffectAtLocation(DURATION_TYPE_PERMANENT,
                                                      eSummon,
                                                    GetOppositeLocation(oTarget));*/
				ApplyEffectToObject(DURATION_TYPE_PERMANENT,
                                                      eSummon,
                                                    oTarget);
                          
                DelayCommand(3.0,DoAdultDragonDeckCardRecord("c_reddragon",oTarget));
				return;
	}
	else if(GetIsObjectValid(oRedDragon) && nIsAdultFighting == TRUE && nAdultDragonOut == 1)
	{
		return;
	}
	else if(GetIsObjectValid(oRedDragon) && nIsAdultFighting != TRUE && nAdultDragonOut == 1)
	{
	    //combat is over. destroy the red dragon.
		RemoveSummonedAssociate(oTarget,oRedDragon);
	    DestroyObject(oRedDragon,0.0);	
	   	DestroyObject(GetLocalObject(oTarget,"X0_DECK_HATCH_OBJECT"),0.0);	
	    DestroyObject(OBJECT_SELF,0.0);	
		DeleteLocalInt(oTarget,"nAdultDragonOut");
	    DeleteLocalObject(oTarget,"X0_DECK_HATCH");
	    DeleteLocalObject(oTarget,"oRedDragon");
		
	   return;
	}
	else if(!GetIsObjectValid(oHatch) && nAdultDragonOut == 0)
	{
	   //summon a replacement hatchling
        AssignCommand(oTarget, DoHatchlingDeckCardSummon());
    }
}