// ----------------------------------------------------------------------
// Snektech
// ----------------------------------------------------------------------
//
// Spawn flags for SnekTech items handled here.
//

enum SnekTechSpawnFlags
{
    SNEKTECH_GRETCHENCOUNTER = 0,
    SNEKTECH_JUMPERCABLES    = 1,
    SNEKTECH_CACOPLUSHIE     = 2,
    SNEKTECH_SPRAYCAN        = 3
}

class SnekTechEventHandler : EventHandler
{
    bool GetItemEnabled(int item)
    {
        int spawnFlags = CVar.GetCVar("snektech_spawnflags").GetInt();
        if(spawnFlags & (1 << item)) {
            return true;
        }
        return false;
    }

    void DoSnekTechBackpackSpawnCheck(
        Actor maybePack,
        int itemFlagIndex,
        String itemClass)
    {
        HDBackpack pack = HDBackpack(maybePack);
        if(pack && !pack.owner) {
            if(!GetItemEnabled(itemFlagIndex)) {
                pack.storage.DestroyItem(itemClass);
            }
        }
    }

    void DoSnekTechReplacement(
        int itemFlagIndex,
        class<Actor> Replacee,
        class<Actor> Replacement,
        int chance,
        ReplaceEvent e)
    {
        if(GetItemEnabled(itemFlagIndex)) {
            if(e.Replacee == Replacee) {
                if(random() < chance) {
                    e.Replacement = Replacement;
                }
            }
        }
    }

    override void WorldThingSpawned(WorldEvent e)
    {
        if(!e.Thing) {
            return;
        }

        // Disable drop useless ammo for batteries.
        HDBattery bat = HDBattery(e.Thing);
        if(bat) {
            bat.ItemsThatUseThis.Push("GretchenCounter");
            bat.ItemsThatUseThis.Push("JumperCablesUsable");
        }

        // Delete disabled items from backpacks that just spawned.
        DoSnekTechBackpackSpawnCheck(
            e.Thing,
            SNEKTECH_GRETCHENCOUNTER,
            "GretchenCounter");

        DoSnekTechBackpackSpawnCheck(
            e.Thing,
            SNEKTECH_JUMPERCABLES,
            "JumperCablesUsable");

        DoSnekTechBackpackSpawnCheck(
            e.Thing,
            SNEKTECH_CACOPLUSHIE,
            "KiriCacodemonPlushie");

        DoSnekTechBackpackSpawnCheck(
            e.Thing,
            SNEKTECH_SPRAYCAN,
            "Sprayer");
    }

	override void CheckReplacement(ReplaceEvent e)
	{
		if(!e.Replacement) {
			return;
		}

        if(e.isFinal) {
            return;
        }

        DoSnekTechReplacement(
            SNEKTECH_GRETCHENCOUNTER,
            "Stimpack", "GretchenCounter",
            12, e);

        DoSnekTechReplacement(
            SNEKTECH_JUMPERCABLES,
            "Allmap", "JumperCablesUsable",
            12, e);

        DoSnekTechReplacement(
            SNEKTECH_CACOPLUSHIE,
            "BlurSphere", "KiriCacodemonPlushie",
            6, e);

        // Note: No replacements for spray cans.
    }

}
