package org.allaymc.server.item.component;

import lombok.extern.slf4j.Slf4j;
import org.allaymc.api.block.dto.PlayerInteractInfo;
import org.allaymc.api.entity.EntityInitInfo;
import org.allaymc.api.entity.type.EntityType;
import org.allaymc.api.item.ItemStackInitInfo;
import org.allaymc.api.item.component.ItemSpawnEggBaseComponent;
import org.allaymc.api.world.Dimension;
import org.allaymc.server.entity.data.EntityId;
import org.allaymc.server.world.physics.AllayEntityPhysicsEngine;
import org.joml.Vector3ic;

import java.util.function.Supplier;

/**
 * @author IWareQ
 */
@Slf4j
public class ItemSpawnEggBaseComponentImpl extends ItemBaseComponentImpl implements ItemSpawnEggBaseComponent {
    protected final Supplier<EntityType<?>> entityType;

    public ItemSpawnEggBaseComponentImpl(ItemStackInitInfo initInfo, Supplier<EntityType<?>> entityTypeSupplier) {
        super(initInfo);
        this.entityType = entityTypeSupplier;
    }

    public ItemSpawnEggBaseComponentImpl(ItemStackInitInfo initInfo, EntityId entityId) {
        this(initInfo, entityId::getEntityType);
    }

    @Override
    public EntityType<?> getEntityType() {
        return entityType.get();
    }

    @Override
    public boolean useItemOnBlock(Dimension dimension, Vector3ic placeBlockPos, PlayerInteractInfo interactInfo) {
        if (interactInfo == null) {
            return false;
        }

        var clickedPos = interactInfo.clickedPos();
        var clickedBlockPos = interactInfo.clickedBlockPos();
        var entity = getEntityType().createEntity(
                EntityInitInfo.builder()
                        .dimension(dimension)
                        .pos(
                                (double) clickedPos.x() + clickedBlockPos.x(),
                                // Add FAT_AABB_MARGIN to prevent the spawned entity from clipping into the ground
                                (double) clickedPos.y() + clickedBlockPos.y() + AllayEntityPhysicsEngine.FAT_AABB_MARGIN,
                                (double) clickedPos.z() + clickedBlockPos.z()
                        )
                        .build()
        );
        dimension.getEntityManager().addEntity(entity);
        return true;
    }
}
