package top.r3944realms.lib39.core.sync;

import net.minecraft.nbt.CompoundTag;
import net.minecraft.nbt.Tag;
import net.minecraft.world.entity.Entity;
import org.jetbrains.annotations.NotNull;

/**
 * The interface Lib 39 sync data holder.
 */
public interface ILib39SyncDataHolder {
    /**
     * Lib 39 get sync data compound tag.
     *
     * @return the compound tag
     */
    CompoundTag lib39$getSyncData();

    /**
     * Lib 39 set sync data.
     *
     * @param tag the tag
     */
    void lib39$setSyncData(CompoundTag tag);

    /**
     * Lib 39 inject save sync data compound tag.
     *
     * @param tag the tag
     * @return the compound tag
     */
    default CompoundTag lib39$injectSaveSyncData(CompoundTag tag) {
        if (lib39$getSyncData() != null && !lib39$getSyncData().isEmpty()) {
            tag.put("Lib39Data", lib39$getSyncData());
        }
        return tag;
    }

    /**
     * Lib 39 inject load sync data.
     *
     * @param tag the tag
     */
    default void lib39$injectLoadSyncData(@NotNull CompoundTag tag) {
        if (tag.contains("Lib39Data", Tag.TAG_COMPOUND)) {
            lib39$setSyncData(tag.getCompound("Lib39Data"));
        }
    }

    /**
     * Save sync data.
     *
     * @param syncData the sync data
     */
    default void saveSyncData(@NotNull NBTEntitySyncData syncData) {
        lib39$getSyncData().put(syncData.id.toDebugFileName(), syncData.serializeNBT());
    }

    /**
     * Load sync data.
     *
     * @param syncData the sync data
     */
    default void loadSyncData(NBTEntitySyncData syncData) {
        if (syncData != null && lib39$getSyncData().contains(syncData.id.toDebugFileName())) {
            syncData.deserializeNBT(lib39$getSyncData().getCompound(syncData.id.toDebugFileName()));
        }
    }

    /**
     * Gets holder.
     *
     * @param entity the entity
     * @return the holder
     */
    static ILib39SyncDataHolder getHolder(Entity entity) {
        return (ILib39SyncDataHolder) entity;
    }
}
