/*
 * Copyright (c) 2026 盐灯水母
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at https://mozilla.org/MPL/2.0/.
 */

package com.remains_cave.item.component;

import com.mojang.serialization.Codec;
import com.mojang.serialization.codecs.RecordCodecBuilder;
import net.minecraft.network.RegistryFriendlyByteBuf;
import net.minecraft.network.codec.ByteBufCodecs;
import net.minecraft.network.codec.StreamCodec;
import net.minecraft.world.item.ItemStack;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public record QuiverContent(List<ItemStack> arrows) {
    public static final int MAX_SLOTS = 3;

    public static final Codec<QuiverContent> CODEC = RecordCodecBuilder.create(instance -> instance.group(
            ItemStack.OPTIONAL_CODEC.listOf().fieldOf("arrows").forGetter(QuiverContent::arrows)
    ).apply(instance, QuiverContent::new));

    public static final StreamCodec<RegistryFriendlyByteBuf, QuiverContent> STREAM_CODEC =
            ByteBufCodecs.fromCodecWithRegistries(CODEC);

    // 显式构造函数，确保列表大小固定且不含 null
    public QuiverContent(List<ItemStack> arrows) {
        List<ItemStack> list = new ArrayList<>(arrows);
        if (list.size() > MAX_SLOTS) {
            list = list.subList(0, MAX_SLOTS);
        }
        while (list.size() < MAX_SLOTS) {
            list.add(ItemStack.EMPTY);
        }
        this.arrows = Collections.unmodifiableList(list);
    }

    public static QuiverContent EMPTY() {
        return new QuiverContent(Collections.nCopies(MAX_SLOTS, ItemStack.EMPTY));
    }
}