/*
 * This file is part of Sponge, licensed under the MIT License (MIT).
 *
 * Copyright (c) SpongePowered <https://www.spongepowered.org>
 * Copyright (c) contributors
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */
package org.spongepowered.common.event.tracking.phase.block;

import net.minecraft.entity.item.EntityItem;
import org.spongepowered.api.Sponge;
import org.spongepowered.api.entity.Entity;
import org.spongepowered.api.event.CauseStackManager.StackFrame;
import org.spongepowered.api.event.SpongeEventFactory;
import org.spongepowered.api.event.cause.EventContextKeys;
import org.spongepowered.api.event.cause.entity.spawn.SpawnTypes;
import org.spongepowered.api.event.entity.SpawnEntityEvent;
import org.spongepowered.api.event.item.inventory.DropItemEvent;
import org.spongepowered.api.world.LocatableBlock;
import org.spongepowered.api.world.Location;
import org.spongepowered.api.world.World;
import org.spongepowered.common.SpongeImpl;
import org.spongepowered.common.entity.EntityUtil;
import org.spongepowered.common.event.tracking.context.GeneralizedContext;
import org.spongepowered.common.event.tracking.TrackingUtil;
import org.spongepowered.common.interfaces.world.IMixinWorldServer;

import java.util.List;
import java.util.stream.Collectors;

final class BlockDecayPhaseState extends BlockPhaseState {

    BlockDecayPhaseState() {
    }

    @Override
    public GeneralizedContext createPhaseContext() {
        return super.createPhaseContext()
            .addCaptures();
    }

    @SuppressWarnings("unchecked")
    @Override
    public void unwind(GeneralizedContext context) {
        final LocatableBlock locatable = context.getSource(LocatableBlock.class)
                .orElseThrow(TrackingUtil.throwWithContext("Expected to be ticking over at a location!", context));
        final Location<World> worldLocation = locatable.getLocation();
        final IMixinWorldServer mixinWorld = ((IMixinWorldServer) worldLocation.getExtent());

        context.getCapturedItemsSupplier()
                .acceptAndClearIfNotEmpty(items -> {
                    // Nothing happens here yet for some reason.
                });
        try (StackFrame frame = Sponge.getCauseStackManager().pushCauseFrame()) {
            Sponge.getCauseStackManager().addContext(EventContextKeys.SPAWN_TYPE, SpawnTypes.BLOCK_SPAWNING);
            context.addNotifierAndOwnerToCauseStack();
            context.getCapturedEntitySupplier()
                    .acceptAndClearIfNotEmpty(entities -> {
                        final SpawnEntityEvent event =
                                SpongeEventFactory.createSpawnEntityEvent(Sponge.getCauseStackManager().getCurrentCause(), entities);
                        SpongeImpl.postEvent(event);
                        if (!event.isCancelled()) {
                            for (Entity entity : event.getEntities()) {
                                EntityUtil.getMixinWorld(entity).forceSpawnEntity(entity);
                            }
                        }
                    });
            context.getCapturedBlockSupplier()
                    .acceptAndClearIfNotEmpty(blocks -> TrackingUtil.processBlockCaptures(blocks, this, context));
            context.getCapturedItemStackSupplier()
                    .acceptAndClearIfNotEmpty(drops -> {
                        final List<EntityItem> items = drops.stream()
                                .map(drop -> drop.create(mixinWorld.asMinecraftWorld()))
                                .collect(Collectors.toList());
                        final List<Entity> entities = (List<Entity>) (List<?>) items;
                        if (!entities.isEmpty()) {
                            DropItemEvent.Custom event =
                                    SpongeEventFactory.createDropItemEventCustom(Sponge.getCauseStackManager().getCurrentCause(), entities);
                            SpongeImpl.postEvent(event);
                            if (!event.isCancelled()) {
                                for (Entity droppedItem : event.getEntities()) {
                                    mixinWorld.forceSpawnEntity(droppedItem);
                                }
                            }
                        }
                    });
        }
    }
}

@@ -3002,16 +3002,198 @@
 nt());%0A%0A
+        try (StackFrame frame = Sponge.getCauseStackManager().pushCauseFrame()) %7B%0A            frame.pushCause(locatable);%0A            context.addNotifierAndOwnerToCauseStack();%0A%0A    
         
@@ -3215,13 +3215,13 @@
 ured
-Items
+Block
 Supp
@@ -3219,32 +3219,36 @@
 BlockSupplier()%0A
+    
                 
@@ -3277,83 +3277,267 @@
 pty(
-items -%3E %7B%0A                    // Nothing happens here yet for some reason.
+blocks -%3E TrackingUtil.processBlockCaptures(blocks, this, context));%0A%0A            frame.addContext(EventContextKeys.SPAWN_TYPE, SpawnTypes.BLOCK_SPAWNING);%0A            context.getCapturedItemsSupplier()%0A                    .acceptAndClearIfNotEmpty(items -%3E %7B
 %0A   
@@ -3549,28 +3549,24 @@
         
-%7D);%0A
         
 try (Sta
@@ -3561,244 +3561,459 @@
     
-try (StackFrame frame = Sponge.getCauseStackManager().pushCauseFrame()) %7B%0A            Sponge.getCauseStackManager().addContext(EventContextKeys.SPAWN_TYPE, SpawnTypes.BLOCK_SPAWNING);%0A            context.addNotifierAndOwnerToCauseStack(
+final SpawnEntityEvent event = SpongeEventFactory.createSpawnEntityEvent(frame.getCurrentCause(), items);%0A                        SpongeImpl.postEvent(event);%0A                        if (!event.isCancelled()) %7B%0A                            for (Entity entity : event.getEntities()) %7B%0A                                EntityUtil.getMixinWorld(entity).forceSpawnEntity(entity);%0A                            %7D%0A                        %7D%0A                    %7D
 );%0A 
@@ -4252,37 +4252,13 @@
 ent(
-Sponge.getCauseStackManager()
+frame
 .get
@@ -4636,170 +4636,8 @@
 %7D);%0A
-            context.getCapturedBlockSupplier()%0A                    .acceptAndClearIfNotEmpty(blocks -%3E TrackingUtil.processBlockCaptures(blocks, this, context));%0A
     
@@ -5241,37 +5241,13 @@
 tom(
-Sponge.getCauseStackManager()
+frame
 .get

Fix saplings (and apples) not dropping from decaying leaves and change the addition order of EventContextKeys