package top.r3944realms.lib39.core.sync;

import net.fabricmc.fabric.api.lookup.v1.entity.EntityApiLookup;
import net.minecraft.resources.Identifier;
import net.minecraft.world.entity.Entity;
import org.jetbrains.annotations.Nullable;
import top.r3944realms.lib39.core.event.FabricCommonEventHandler;

/**
 * The type Sync lookup provider.
 *
 * @param <T> the type parameter
 */
public abstract class SyncLookupProvider<T extends NBTEntitySyncData> implements EntityApiLookup.EntityApiProvider<T, Void> {
    /**
     * Create empty lookup t.
     *
     * @param entity the entity
     * @return the t
     */
    protected abstract T createEmptyLookup(Entity entity);

    /**
     * Gets id.
     *
     * @return the id
     */
    protected abstract Identifier getId();
    @SuppressWarnings("unchecked")
    @Override
    public @Nullable T find(Entity entity, Void context) {
        return FabricCommonEventHandler.getSyncData2Manager().getManager(getId()).map(
                objectISyncDataISyncManager -> {
                    ISyncData<?> iSyncData = objectISyncDataISyncManager.getSyncMap().get(entity.getUUID());
                    if (iSyncData instanceof NBTEntitySyncData syncData) {
                        return (T) syncData;
                    }
                    T defaultLookup = createEmptyLookup(entity);
                    ILib39SyncDataHolder.getHolder(entity).loadSyncData(defaultLookup);
                    objectISyncDataISyncManager.getSyncMap().put(entity.getUUID(), defaultLookup);
                    return defaultLookup;
                }
        ).orElse(createEmptyLookup(entity));
    }
}
