// 
// Decompiled by Procyon v0.6.0
// 

package com.hypixel.hytale.builtin.mounts;

import com.hypixel.hytale.protocol.Packet;
import com.hypixel.hytale.server.core.universe.world.World;
import com.hypixel.hytale.component.Store;
import com.hypixel.hytale.server.core.universe.PlayerRef;
import com.hypixel.hytale.protocol.MountController;
import com.hypixel.hytale.component.ComponentAccessor;
import com.hypixel.hytale.component.Ref;
import com.hypixel.hytale.server.core.entity.entities.Player;
import com.hypixel.hytale.server.core.universe.world.storage.EntityStore;
import com.hypixel.hytale.protocol.packets.interaction.DismountNPC;
import com.hypixel.hytale.server.core.io.handlers.IPacketHandler;
import com.hypixel.hytale.server.core.io.handlers.SubPacketHandler;

public class MountGamePacketHandler implements SubPacketHandler
{
    private final IPacketHandler packetHandler;
    static final /* synthetic */ boolean $assertionsDisabled;
    
    public MountGamePacketHandler(final IPacketHandler packetHandler) {
        this.packetHandler = packetHandler;
    }
    
    @Override
    public void registerHandlers() {
        this.packetHandler.registerHandler(294, protoPacket -> this.handle((DismountNPC)protoPacket));
    }
    
    public void handle(final DismountNPC packet) {
        final PlayerRef playerRef = this.packetHandler.getPlayerRef();
        final Ref<EntityStore> ref = playerRef.getReference();
        if (ref == null || !ref.isValid()) {
            throw new RuntimeException("Unable to process DismountNPC packet. Player ref is invalid!");
        }
        final Store<EntityStore> store = ref.getStore();
        final EntityStore entityStore = store.getExternalData();
        final World world = entityStore.getWorld();
        world.execute(() -> {
            final Player playerComponent = store.getComponent(ref, Player.getComponentType());
            if (!MountGamePacketHandler.$assertionsDisabled && playerComponent == null) {
                throw new AssertionError();
            }
            else {
                final MountedComponent mounted = store.getComponent(ref, MountedComponent.getComponentType());
                if (mounted == null) {
                    final int mountEntityId = playerComponent.getMountEntityId();
                    playerComponent.setMountEntityId(0);
                    MountPlugin.dismountNpc(store, mountEntityId);
                }
                else if (mounted.getControllerType() == MountController.BlockMount) {
                    store.tryRemoveComponent(ref, MountedComponent.getComponentType());
                }
            }
        });
    }
}
