/*
 * Original project: RedEnvelope by KaguyaStudio-MC
 * Original project link: https://github.com/KaguyaStudio-MC/RedEnvelope
 * Modified by: LeisureTimeDock
 * This file is part of RedEnvelope
 * Licensed under Camellia License Version 1.0
 */

/*
 * Original project: RedEnvelope by KaguyaStudio-MC
 * Original project link: https://github.com/KaguyaStudio-MC/RedEnvelope
 * Modified by: LeisureTimeDock
 * This file is part of RedEnvelope
 * Licensed under Camellia License Version 1.0
 */

package top.leisuretimedock.redenvelope.core.capability;

import net.minecraft.core.Direction;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.world.entity.Entity;
import net.minecraft.world.entity.player.Player;
import net.minecraftforge.common.capabilities.*;
import net.minecraftforge.common.util.LazyOptional;
import net.minecraftforge.event.AttachCapabilitiesEvent;
import net.minecraftforge.eventbus.api.SubscribeEvent;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import top.leisuretimedock.redenvelope.RedEnvelope;


public class RECapability {

    public static final Capability<RedEnvelopeStorage> HONGBAO_STORAGE = CapabilityManager.get(new CapabilityToken<>() {});

    public static void register(@NotNull RegisterCapabilitiesEvent event) {
        event.register(RedEnvelopeStorage.class);
    }

    @SubscribeEvent
    public static void onAttachPlayerCapabilities(@NotNull AttachCapabilitiesEvent<Entity> event) {
        if (event.getObject() instanceof Player) {
            event.addCapability(
                    RedEnvelope.rl("hongbao_storage"),
                    new Provider()
            );
        }

    }
    private static class Provider implements ICapabilitySerializable<CompoundTag> {
        private final RedEnvelopeStorage storage = new RedEnvelopeStorage();
        private final LazyOptional<RedEnvelopeStorage> optional = LazyOptional.of(() -> storage);

        @Override
        public <T> @NotNull LazyOptional<T> getCapability(@NotNull Capability<T> cap, @Nullable Direction side) {
            return HONGBAO_STORAGE.orEmpty(cap, optional);
        }

        @Override
        public CompoundTag serializeNBT() {
            return storage.serializeNBT();
        }

        @Override
        public void deserializeNBT(CompoundTag nbt) {
            storage.deserializeNBT(nbt);
        }
    }
}
