// Randomly places the key in one of the 4 chests.
// Go, go, replayability!

void main()
{
    object oPC = GetLastUsedBy();
    object oDoorA = GetObjectByTag("PortcullisA");
    object oDoorB = GetObjectByTag("PortcullisB");
    object oDoorC = GetObjectByTag("PortcullisC");
    object oDoorD = GetObjectByTag("PortcullisD");
    object oChestA = GetObjectByTag("ChestA");
    object oChestB = GetObjectByTag("ChestB");
    object oChestC = GetObjectByTag("ChestC");
    object oChestD = GetObjectByTag("ChestD");
    effect eKnock = EffectVisualEffect(VFX_IMP_KNOCK);
    location lFireA = GetLocation(GetWaypointByTag("WP_FIRE_A"));
    location lFireB = GetLocation(GetWaypointByTag("WP_FIRE_B"));
    location lFireC = GetLocation(GetWaypointByTag("WP_FIRE_C"));
    location lFireD = GetLocation(GetWaypointByTag("WP_FIRE_D"));


    if (GetIsPC(oPC) && GetLocalInt(OBJECT_SELF, "Completed") != TRUE) {
        AssignCommand(oPC, ActionPlayAnimation(ANIMATION_LOOPING_GET_MID, 0.5, 0.5));
        ActionPlayAnimation(ANIMATION_PLACEABLE_ACTIVATE, 0.5, 0.5);
        switch (Random(4)) {
            case 0:
                CreateItemOnObject("asmallgoldenkey", oChestA, 1);
                break;
            case 1:
                CreateItemOnObject("asmallgoldenkey", oChestB, 1);
                break;
            case 2:
                CreateItemOnObject("asmallgoldenkey", oChestC, 1);
                break;
            case 3:
                CreateItemOnObject("asmallgoldenkey", oChestD, 1);
                break;
                }
        DelayCommand(2.0, SetPlotFlag(oDoorA, FALSE));
        DelayCommand(2.0, SetPlotFlag(oDoorB, FALSE));
        DelayCommand(2.0, SetPlotFlag(oDoorC, FALSE));
        DelayCommand(2.0, SetPlotFlag(oDoorD, FALSE));
        DelayCommand(2.1, SetLocked(oDoorA, FALSE));
        DelayCommand(2.1, SetLocked(oDoorB, FALSE));
        DelayCommand(2.1, SetLocked(oDoorC, FALSE));
        DelayCommand(2.1, SetLocked(oDoorD, FALSE));
        DelayCommand(2.2, ApplyEffectAtLocation(DURATION_TYPE_INSTANT, eKnock, lFireA, 2.0f));
        DelayCommand(2.2, ApplyEffectAtLocation(DURATION_TYPE_INSTANT, eKnock, lFireB, 2.0f));
        DelayCommand(2.2, ApplyEffectAtLocation(DURATION_TYPE_INSTANT, eKnock, lFireC, 2.0f));
        DelayCommand(2.5, FloatingTextStringOnCreature("You hear the small plink of an item being dropped into a wooden chest.", oPC));
        DelayCommand(3.0, SetEncounterActive(TRUE, GetObjectByTag("SpiderGroup")));
        SetLocalInt(OBJECT_SELF, "Completed", TRUE);
    }

    else {
        PlaySound("as_dr_locked3");
        ActionSpeakString("It appears as though this lever could only be used once.");
    }
}
