#include "cas_casinoinc"

void CasinoNotification(string sMessage);

// Notify all other listeners with the same tag in the same area
void NotifyOtherListeners(object oExclude, object oArea)
{
    int i = 0;
    object oL = GetObjectByTag("C_CAS_GLORYLISTEN", i);
    while (GetIsObjectValid(oL))
    {
        if (oL != oExclude && GetArea(oL) == oArea)
        {
            AssignCommand(oL, SpeakString("Someone approaches."));
        }
        i++;
        oL = GetObjectByTag("C_CAS_GLORYLISTEN", i);
    }
}

void main()
{
    object oEnteringPC = GetEnteringObject();
    if (!GetIsPC(oEnteringPC)) return;

    string sVariableName = GetLocalString(OBJECT_SELF, "VariableName");
    if (sVariableName == "") return;

    int nVariableValue = GetLocalInt(OBJECT_SELF, "VariableValue");
    SetLocalInt(oEnteringPC, sVariableName, nVariableValue);

    if (GetLocalInt(OBJECT_SELF, "SPAWN_LISTENER") == 1)
    {
        // Per-PC key so each player can have their own listener for this trigger
        string sKey = "CAS_LISTENER_" + GetTag(OBJECT_SELF);
        object oExistingForPC = GetLocalObject(oEnteringPC, sKey);

        object oArea = GetArea(OBJECT_SELF);

        if (!GetIsObjectValid(oExistingForPC))
        {
            location lSpawn = GetLocation(oEnteringPC);
            object oListener = CreateObject(OBJECT_TYPE_CREATURE, "cas_glorylisten", lSpawn, FALSE);

            // Tie listener to this PC + this trigger
            SetLocalObject(oEnteringPC, sKey, oListener);
            SetLocalObject(oListener, "OWNER_PC", oEnteringPC);

            // Make the listener actually listen and route to your script
            SetLocalString(oListener, "EVENT_AI_CONVERSATION", "cas_repeatspeech");
            SetListening(oListener, TRUE);
            SetListenPattern(oListener, "**", 100);

            // Your routing setup (leave as you currently use it)
            if (sVariableName == "I_AM_IN_HOLE" && nVariableValue == 1)
            {
                SetLocalString(oListener, "sSEND_TO", "FROM_HOLE"); // or INTO_HOLE if you swapped earlier
                CasinoNotification("<cU˙˙>The gloryhole is now occupied...</c>");
            }
            else if (sVariableName == "NOT_IN_HOLE" && nVariableValue == 1)
            {
                SetLocalString(oListener, "sSEND_TO", "INTO_HOLE"); // or FROM_HOLE if swapped
            }

            // Debug
            SendMessageToPC(oEnteringPC, "[OnEnter] Listener spawned + bound to you for trigger " + GetTag(OBJECT_SELF));

            // Inform any other listeners in the same area
            NotifyOtherListeners(oListener, oArea);
        }
        else
        {
            // Already have a listener for this PC/trigger: still inform other listeners
            NotifyOtherListeners(oExistingForPC, oArea);
        }
    }
}
