package top.r3944realms.lib39.client.renderer.block;

import com.mojang.authlib.GameProfile;
import com.mojang.blaze3d.vertex.PoseStack;
import com.mojang.blaze3d.vertex.VertexConsumer;
import com.mojang.math.Axis;
import net.minecraft.client.renderer.MultiBufferSource;
import net.minecraft.client.renderer.RenderType;
import net.minecraft.client.renderer.blockentity.BlockEntityRenderer;
import net.minecraft.client.renderer.blockentity.BlockEntityRendererProvider;
import net.minecraft.client.renderer.texture.OverlayTexture;
import net.minecraft.core.Direction;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.world.level.block.state.BlockState;
import org.jetbrains.annotations.NotNull;
import top.r3944realms.lib39.client.model.DollModel;
import top.r3944realms.lib39.client.renderer.item.DollItemRenderer;
import top.r3944realms.lib39.content.block.DollBlock;
import top.r3944realms.lib39.content.block.blockentity.DollBlockEntity;
import top.r3944realms.lib39.util.lang.Pair;

/**
 * The type Doll block entity renderer.
 */
public class DollBlockEntityRenderer implements BlockEntityRenderer<DollBlockEntity> {
    private final DollModel dollModel;

    /**
     * Instantiates a new Doll block entity renderer.
     *
     * @param context the context
     */
    public DollBlockEntityRenderer(BlockEntityRendererProvider.@NotNull Context context) {
        this.dollModel = new DollModel(context.bakeLayer(DollModel.LAYER_LOCATION));
    }

    @Override
    public void render(@NotNull DollBlockEntity dollBlockEntity, float partialTick, @NotNull PoseStack poseStack, @NotNull MultiBufferSource buffer, int packedLight, int packedOverlay) {
        BlockState blockState = dollBlockEntity.getBlockState();
        if (blockState.getBlock() instanceof DollBlock) {
            Direction facing = blockState.getValue(DollBlock.FACING);
            GameProfile profile = dollBlockEntity.getOwnerProfile();
            Pair<ResourceLocation, Boolean> resourceLocationBooleanPair = DollItemRenderer.loadSkin(profile);
            poseStack.pushPose();
            poseStack.translate(0.5, 1.5, 0.5);
            poseStack.scale(1.0F, -1.0F, -1.0F);
            float rotation = facing.toYRot();
            poseStack.mulPose(Axis.YP.rotationDegrees(rotation));
            VertexConsumer vertexConsumer = buffer.getBuffer(RenderType.entityTranslucent(resourceLocationBooleanPair.first));
            this.dollModel.slim = resourceLocationBooleanPair.second;
            this.dollModel.renderToBuffer(poseStack, vertexConsumer, packedLight, OverlayTexture.NO_OVERLAY, 1.0F, 1.0F, 1.0F, 1.0F);
            poseStack.popPose();
        }
    }
}
