package com.tiedup.remake.network.bounty;

import com.tiedup.remake.bounty.Bounty;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Supplier;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.nbt.ListTag;
import net.minecraft.nbt.Tag;
import net.minecraft.network.FriendlyByteBuf;
import net.minecraftforge.api.distmarker.Dist;
import net.minecraftforge.api.distmarker.OnlyIn;
import net.minecraftforge.fml.loading.FMLEnvironment;
import net.minecraftforge.network.NetworkEvent;

/**
 * Packet: Server sends bounty list to client.
 *
 *
 * Flow: Server → Client (opens BountyListScreen)
 */
public class PacketSendBounties {

    private final List<Bounty> bounties;
    private final boolean isAdmin;

    public PacketSendBounties(List<Bounty> bounties, boolean isAdmin) {
        this.bounties = bounties;
        this.isAdmin = isAdmin;
    }

    public void encode(FriendlyByteBuf buf) {
        buf.writeBoolean(isAdmin);

        // Serialize bounties as NBT list
        ListTag listTag = new ListTag();
        for (Bounty bounty : bounties) {
            listTag.add(bounty.save());
        }
        CompoundTag wrapper = new CompoundTag();
        wrapper.put("bounties", listTag);
        buf.writeNbt(wrapper);
    }

    public static PacketSendBounties decode(FriendlyByteBuf buf) {
        boolean isAdmin = buf.readBoolean();

        CompoundTag wrapper = buf.readNbt();
        List<Bounty> bounties = new ArrayList<>();

        if (wrapper != null && wrapper.contains("bounties")) {
            ListTag listTag = wrapper.getList("bounties", Tag.TAG_COMPOUND);
            for (int i = 0; i < listTag.size(); i++) {
                bounties.add(Bounty.load(listTag.getCompound(i)));
            }
        }

        return new PacketSendBounties(bounties, isAdmin);
    }

    public void handle(Supplier<NetworkEvent.Context> ctx) {
        ctx
            .get()
            .enqueueWork(() -> {
                if (FMLEnvironment.dist == Dist.CLIENT) {
                    handleClient();
                }
            });
        ctx.get().setPacketHandled(true);
    }

    @OnlyIn(Dist.CLIENT)
    private void handleClient() {
        net.minecraft.client.Minecraft.getInstance().setScreen(
            new com.tiedup.remake.client.gui.screens.BountyListScreen(
                bounties,
                isAdmin
            )
        );
    }
}
