package com.leisuretimedock.blasttravelreborn.network.toClient;

import com.leisuretimedock.blasttravelreborn.content.entity.CannonEntity;
import com.leisuretimedock.blasttravelreborn.util.PlayerEntityDuck;
import net.minecraft.client.multiplayer.ClientPacketListener;
import net.minecraft.network.FriendlyByteBuf;
import net.minecraft.world.entity.Entity;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.phys.Vec3;
import net.minecraftforge.fml.loading.FMLEnvironment;
import net.minecraftforge.network.NetworkEvent;
import org.jetbrains.annotations.Nullable;

import java.util.Optional;
import java.util.function.Supplier;

public record FireCannonPayload(int cannonId, Optional<Integer> launchedId, double velocityX, double velocityY, double velocityZ) {
    public FireCannonPayload(FriendlyByteBuf buf) {
        this(
                buf.readInt(), buf.readOptional(FriendlyByteBuf::readInt),
                buf.readDouble(), buf.readDouble(), buf.readDouble()
        );
    }
    public FireCannonPayload(CannonEntity cannon, @Nullable Player launched, Vec3 velocity) {
        this(
                cannon.getId(), Optional.ofNullable(launched).map(Entity::getId),
                velocity.x, velocity.y, velocity.z
        );
    }
    public static FireCannonPayload read(FriendlyByteBuf buf) {
        return new FireCannonPayload(buf);
    }
    public void write(FriendlyByteBuf buf) {
        buf.writeInt(cannonId);
        buf.writeOptional(launchedId, FriendlyByteBuf::writeInt);
        buf.writeDouble(velocityX);
        buf.writeDouble(velocityY);
        buf.writeDouble(velocityZ);
    }
    public void handler(Supplier<NetworkEvent.Context> ctx) {
        NetworkEvent.Context context = ctx.get();
        if (context.getNetworkManager().getPacketListener() instanceof ClientPacketListener clientPacketListener) {
            context.enqueueWork(() -> {
                if (hasPlayer()) {
                    //noinspection OptionalGetWithoutIsPresent
                    if (clientPacketListener.getLevel().getEntity(launchedId.get()) instanceof Player launchedPlayer) {

                        // 立即停止乘坐并设置速度
                        if (launchedPlayer.isPassenger()) {
                            launchedPlayer.stopRiding();
                        }

                        // 直接设置速度，不要延迟
                        launchedPlayer.setDeltaMovement(velocityX, velocityY, velocityZ);
                        ((PlayerEntityDuck) launchedPlayer).blasttravel$setCannonFlight(true);

                    }
                }

                // 处理炮实体效果
                Entity entity = clientPacketListener.getLevel().getEntity(cannonId);
                if (entity instanceof CannonEntity cannonEntity) {
                    cannonEntity.fireClient();
                }
            });
            context.setPacketHandled(true);
        }
    }
    private boolean hasPlayer() {
        return launchedId.isPresent();
    }
}
