package com.leisuretimedock.blasttravelreborn.network.toClient;

import net.minecraft.network.FriendlyByteBuf;
import net.minecraft.world.phys.Vec3;
import net.minecraftforge.fml.loading.FMLEnvironment;
import net.minecraftforge.network.NetworkEvent;
import org.jetbrains.annotations.NotNull;

import java.util.function.Supplier;

public record SyncFlightStatePayload(
        int playerId,
        Vec3 velocity,
        Vec3 position,
        boolean inCannonFlight,
        boolean noPhysics
) {

    public SyncFlightStatePayload(@NotNull FriendlyByteBuf buf) {
        this(
                buf.readInt(),
                new Vec3(buf.readDouble(), buf.readDouble(), buf.readDouble()),
                new Vec3(buf.readDouble(), buf.readDouble(), buf.readDouble()),
                buf.readBoolean(),
                buf.readBoolean()
        );
    }

    public void write(@NotNull FriendlyByteBuf buf) {
        buf.writeInt(playerId);
        buf.writeDouble(velocity.x);
        buf.writeDouble(velocity.y);
        buf.writeDouble(velocity.z);
        buf.writeDouble(position.x);
        buf.writeDouble(position.y);
        buf.writeDouble(position.z);
        buf.writeBoolean(inCannonFlight);
        buf.writeBoolean(noPhysics);
    }
    public static SyncFlightStatePayload read(FriendlyByteBuf buf) {
        return new SyncFlightStatePayload(buf);
    }

    public void handle(Supplier<NetworkEvent.Context> context) {
        context.get().enqueueWork(() -> {
            // 客户端处理逻辑
            net.minecraft.client.Minecraft client = net.minecraft.client.Minecraft.getInstance();
            if (client.level != null) {
                net.minecraft.world.entity.Entity entity = client.level.getEntity(this.playerId);
                if (entity instanceof net.minecraft.world.entity.player.Player player) {
                    // 同步速度
                    player.setDeltaMovement(this.velocity);

                    // 同步位置（如果差异较大）
                    if (player.position().distanceTo(this.position) > 0.1) {
                        player.setPos(this.position);
                    }

                    // 同步飞行状态
                    if (player instanceof com.leisuretimedock.blasttravelreborn.util.PlayerEntityDuck duck) {
                        duck.blasttravel$setCannonFlight(this.inCannonFlight);
                    }

                    player.noPhysics = this.noPhysics;
                    player.hurtMarked = true;

                }
            }
        });
        context.get().setPacketHandled(true);
    }
}