#include "inc_debug"

#include "inc_x_areas"

// Include external destroy area functions
object _CreateArea(string sResRef);
void _DestroyArea(object oArea);

object CreateArea(string sResRef)
{
    object oArea = _CreateArea(sResRef);
    ExecuteScript("inc_ev_creatarea", oArea);
    return oArea;
}

void DoDestroyArea(object oArea)
{
    int bSuccess = _DestroyArea(oArea);
    if (!bSuccess)
    {
        Log("Failed to destroy area: " + GetResRef(oArea));
    }
}

void DestroyArea(object oArea)
{
    if (GetIsAreaNatural(oArea) != AREA_INVALID)
    {
        object oObject = GetFirstObjectInArea(oArea);
        while (oObject != OBJECT_INVALID)
        {
            if (GetObjectType(oObject) == OBJECT_TYPE_DOOR)
            {
                RemoveDoorLink(oObject);
            }
            else if (GetHasInventory(oObject) && !GetLocalInt(oObject, "PC_INIT"))
            {
                if (GetObjectType(oObject) == OBJECT_TYPE_CREATURE)
                {
                    int nSlot;
                    for (nSlot = 0; nSlot < NUM_INVENTORY_SLOTS; nSlot++)
                    {
                        DestroyObject(GetItemInSlot(nSlot, oObject));
                    }
                }
                object oItem = GetFirstItemInInventory(oObject);
                while (GetIsObjectValid(oItem))
                {
                    DestroyObject(oItem);
                    oItem = GetNextItemInInventory(oObject);
                }
            }
            DestroyObject(oObject);
            oObject = GetNextObjectInArea(oArea);
        }

        object oSoundObject = GetFirstSoundObjectInArea(oArea);
        while (GetIsObjectValid(oSoundObject))
        {
            DestroyObject(oSoundObject);
            oSoundObject = GetNextSoundObjectInArea(oArea);
        }

        AssignCommand(GetModule(), DoDestroyArea(oArea));
    }
}

// OnExitArea main function
void main()
{
    object oArea = OBJECT_SELF;
    object oExitingCreature = GetExitingObject();

    // Check if the exiting object is a PC
    if (!GetIsPC(oExitingCreature))
    {
        return; // Only act when a player leaves
    }

    // Check for remaining players in the area
    object oPlayer = GetFirstObjectInArea(oArea);
    while (GetIsObjectValid(oPlayer))
    {
        if (GetIsPC(oPlayer)) // Found another player inside
        {
            return; // Players still inside; don't destroy the area
        }
        oPlayer = GetNextObjectInArea(oArea);
    }

    // No players left in the area, notify the exiting player and destroy the area after a delay
    float fDelay = 5.0; // Delay destruction for 5 seconds
    SendMessageToPC(oExitingCreature, "All players have left. The CTF Tent area will be destroyed in 5 seconds.");

    // Schedule the destruction of the area after the delay
    DelayCommand(fDelay, DestroyArea(oArea));
}
