#include "inc_debug"
#include "s_mmm_inc"

// Function to check if a player is in the same faction (party) as the tent's owner
int IsInParty(object oUser, object oOwner)
{
    object oMember = GetFirstFactionMember(oOwner, TRUE); // Get first PC in the owner's faction
    while (GetIsObjectValid(oMember))
    {
        if (oUser == oMember) // Found the user in the party
            return TRUE;
        
        oMember = GetNextFactionMember(oOwner, TRUE); // Get next party member
    }
    return FALSE;
}

// Function to destroy the CTF Tent area
void DestroyCTFArea(object oArea)
{
    if (GetIsObjectValid(oArea))
    {
        DestroyArea(oArea);
    }
}

void main()
{
    object oPlaceable = OBJECT_SELF;
    object oUser = GetLastUsedBy();
    
    // Check if the placeable already has an owner
    object oOwner = GetLocalObject(oPlaceable, "S_CTF_OWNER");

    if (GetIsObjectValid(oOwner))
    {
        if (!IsInParty(oUser, oOwner))
        {
            SendMessageToPC(oUser, "You need to be in the same party as the person who placed this tent.");
            return;
        }
    }
    else
    {
        // First player to use the tent becomes the "owner"
        SetLocalObject(oPlaceable, "S_CTF_OWNER", oUser);
    }

    // Check if area already exists
    object oCTFArea = GetLocalObject(oPlaceable, "S_CTF_AREA");
    if (!GetIsObjectValid(oCTFArea))
    {
        // Create the Capture the Flag Tent area
        oCTFArea = CreateArea("cas_CTF_home");
        SetLocalObject(oPlaceable, "S_CTF_AREA", oCTFArea);

        // Mark the area as temporary
        SetLocalInt(oCTFArea, "NO_PERSISTENT_LOCATION", TRUE);
        SetLocalInt(oCTFArea, "S_DISABLE_CTF", TRUE);
        SetLocalObject(oCTFArea, "S_CTF_OWNER", oUser);

        // Find the entrance waypoint
        object oCTFWaypoint = GetNearestObjectByTag("WP_CTF_TENT_ENTER", GetFirstObjectInArea(oCTFArea));
        if (!GetIsObjectValid(oCTFWaypoint))
        {
            DestroyCTFArea(oCTFArea);
            SendMessageToPC(oUser, "Error: CTF Tent entrance waypoint not found.");
            return;
        }

        SetLocalObject(oPlaceable, "S_CTF_WAYPOINT", oCTFWaypoint);
    }

    // Teleport user to the tent
    object oWaypoint = GetLocalObject(oPlaceable, "S_CTF_WAYPOINT");
    AssignCommand(oUser, JumpToObject(oWaypoint));

    // Check if all members leave, then destroy the area
    AssignCommand(oCTFArea, DelayCommand(30.0, DestroyCTFArea(oCTFArea)));
}
