package top.r3944realms.lib39.example.content.item;

import net.fabricmc.fabric.api.client.networking.v1.ClientPlayNetworking;
import net.fabricmc.fabric.api.lookup.v1.entity.EntityApiLookup;
import net.minecraft.network.chat.Component;
import net.minecraft.server.level.ServerPlayer;
import net.minecraft.world.entity.Entity;
import net.minecraft.world.entity.LivingEntity;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import top.r3944realms.lib39.Lib39;
import top.r3944realms.lib39.example.content.data.AbstractedTestSyncData;
import top.r3944realms.lib39.example.content.data.FabricTestSyncData;
import top.r3944realms.lib39.example.core.network.FabricClientDataPacket;

/**
 * The type Fabric fabric item.
 */
public class FabricFabricItem extends AbstractFabricItem {

    /**
     * Instantiates a new Fabric fabric item.
     *
     * @param properties the properties
     */
    public FabricFabricItem(Properties properties) {
        super(properties);
    }

    @Override
    protected AbstractedTestSyncData getData(Entity target) {
        return getStaticData(target);
    }

    @Override
    protected void sendClientDataToServer(AbstractedTestSyncData clientData, int targetEntityId) {
        if (ClientPlayNetworking.canSend(FabricClientDataPacket.TYPE)) {
            ClientPlayNetworking.send(new FabricClientDataPacket(clientData, targetEntityId));
        }
    }

    /**
     * Gets static data.
     *
     * @param target the target
     * @return the static data
     */
    public static @Nullable AbstractedTestSyncData getStaticData(Entity target) {
        try {
            AbstractedTestSyncData abstractData = EntityApiLookup.get(FabricTestSyncData.ID, AbstractedTestSyncData.class, Void.class).find(target, null);
            if (abstractData instanceof FabricTestSyncData) {
                return abstractData;
            }
        } catch (Exception e) {
            Lib39.LOGGER.error("[FabricItem] 获取服务器端数据失败", e);
        }
        return null;
    }

    /**
     * Handle client data from packet.
     *
     * @param player         the player
     * @param clientData     the client data
     * @param targetEntityId the target entity id
     */
    public static void handleClientDataFromPacket(@NotNull ServerPlayer player, AbstractedTestSyncData clientData, int targetEntityId) {
        Entity target = player.level().getEntity(targetEntityId);

        if (target instanceof LivingEntity livingTarget) {
            // 获取服务器端数据
            AbstractedTestSyncData serverData = getStaticData(livingTarget);

            if (serverData != null) {
                // 显示双端对比结果
                displayDualEndComparison(player, livingTarget, serverData, clientData);
            } else {
                player.sendSystemMessage(Component.literal("§c无法获取服务器端数据"));
            }
        } else {
            player.sendSystemMessage(Component.literal("§c目标生物不存在或已消失"));
        }
    }
}
