#include "x2_inc_switches"
#include "gun_include"

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

    object oPC = GetPCItemLastUnequippedBy();
    object oItem = GetPCItemLastUnequipped();
    object oGun = GetItemInSlot(INVENTORY_SLOT_RIGHTHAND, oPC);
    string sTag = GetTag(oItem);
    int iStackSize = GetItemStackSize(oItem);
    int iAmmoType = GetLocalInt(oItem, GUN_TEMP_AMMO_TYPE);
    int iBulletCount = GetLocalInt(oItem, GUN_MAGAZINE_BULLET_COUNT);

    // If gun is unequipped, destroy ammo. The bullets are persistently saved on the gun as a variable (GUN_MAGAZINE_BULLET_COUNT)
    //GUN_UnloadAmmo(oPC, oItem);
    if(iBulletCount > 0)
    {
        object oAmmo = GetItemInSlot(INVENTORY_SLOT_ARROWS, oPC);

        if(GetIsObjectValid(oAmmo))
        {
            SetLocalInt(oAmmo, GUN_TEMP_UNLOADING_AMMO, TRUE);
            DestroyObject(oAmmo);
        }

        // Makes the OnEquip script fire when this gun is equipped again.
        DeleteLocalInt(oItem, GUN_TEMP_GUN_EQUIPPED);
    }

    // If ammo magazine is unequipped, convert to ammo box
    else if(GetLocalInt(oItem, GUN_TEMP_UNLOADING_AMMO) == 0)
    {
        string sAmmoBoxTag;
        if(sTag == GUN_FIREARM_MAGAZINE_RESREF)
        {
            sAmmoBoxTag = GUN_NORMAL_AMMO_BOX_PREFIX + IntToString(iAmmoType);
        }
        else if(sTag == GUN_ENHANCED_FIREARM_MAGAZINE_RESREF)
        {
            sAmmoBoxTag = GUN_ENHANCED_AMMO_BOX_PREFIX + IntToString(iAmmoType);
        }
        else if(sTag == GUN_INCENDIARY_FIREARM_MAGAZINE_RESREF)
        {
            sAmmoBoxTag = GUN_INCENDIARY_AMMO_BOX_PREFIX + IntToString(iAmmoType);
        }

        if(sTag == GUN_FIREARM_MAGAZINE_RESREF || sTag == GUN_ENHANCED_FIREARM_MAGAZINE_RESREF || sTag == GUN_INCENDIARY_FIREARM_MAGAZINE_RESREF)
        {
            // Can't find a better way to do this so if the PC unequips a single round of ammo it gets destroyed.
            // Otherwise if a player shoots all of his or her ammo, an ammo box round will replace it. Unless I can
            // find a way to determine when a player unequips the ammo or if they shoot the last ammo, this is the best
            // I can do.
            if(iStackSize > 1)
            {
                CreateItemOnObjectSafe(sAmmoBoxTag, oPC, iStackSize);
            }
            DestroyObject(oItem);


            // Remove persistent bullet counter
            DeleteLocalInt(oGun, GUN_MAGAZINE_BULLET_COUNT);
            // Remove temporary variables
            DeleteLocalInt(oGun, GUN_TEMP_AMMO_LOADED_TYPE);
            // Update gun name
            UpdateItemName(oGun);
        }
    }
}