#include "x2_inc_switches"
#include "gun_include"
#include "dcy_include"

void main()
{
    if(GetUserDefinedItemEventNumber() != X2_ITEM_EVENT_EQUIP) return;

    object oPC = GetPCItemLastEquippedBy();
    object oItem = GetPCItemLastEquipped();
    int iBulletCount = GetLocalInt(oItem, GUN_MAGAZINE_BULLET_COUNT);

    // Fires only if there's bullets to create, the temporary "equipped gun" variable is FALSE, and the gun's durability
    // is not at 0%.
    if(iBulletCount > 0 && GetLocalInt(oItem, GUN_TEMP_GUN_EQUIPPED) == FALSE && DCY_GetItemDurability(oItem) != 0)
    {
        struct GunInfoStruct stGunInfo = GUN_GetGunInfo(oItem);
        // Create an ammo magazine on PC and equip it automatically
        object oAmmo;

        // Create the correct ammo type
        int iLoadedType = GetLocalInt(oItem, GUN_TEMP_AMMO_LOADED_TYPE);
        if(iLoadedType == GUN_AMMUNITION_PRIORITY_ENHANCED)
        {
            oAmmo = CreateItemOnObjectSafe(GUN_ENHANCED_FIREARM_MAGAZINE_RESREF, oPC, iBulletCount);
        }
        else if(iLoadedType == GUN_AMMUNITION_PRIORITY_INCENDIARY)
        {
            oAmmo = CreateItemOnObjectSafe(GUN_INCENDIARY_FIREARM_MAGAZINE_RESREF, oPC, iBulletCount);
        }
        // Default to basic ammo if all else fails
        else
        {
            oAmmo = CreateItemOnObjectSafe(GUN_FIREARM_MAGAZINE_RESREF, oPC, iBulletCount);
        }

        // Prevent exploits by making the loaded ammo cursed
        SetItemCursedFlag(oAmmo, TRUE);
        SetLocalInt(oAmmo, GUN_TEMP_AMMO_TYPE, stGunInfo.iAmmoType);

        AssignCommand(oPC, ClearAllActions());
        AssignCommand(oPC, ActionEquipItem(oAmmo, INVENTORY_SLOT_ARROWS));

        // Prevent this from firing on module entry
        SetLocalInt(oItem, GUN_TEMP_GUN_EQUIPPED, TRUE);
    }
}