package com.tiedup.remake.v2.blocks;

import com.tiedup.remake.core.TiedUpMod;
import net.minecraft.core.BlockPos;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.world.level.block.entity.BlockEntityType;
import net.minecraft.world.level.block.state.BlockState;

/**
 * Block entity for Pet Bowl.
 * Used by Master to feed pets. Players must crouch to eat from it.
 */
public class PetBowlBlockEntity extends ObjBlockEntity {

    public static final ResourceLocation MODEL_LOCATION =
        ResourceLocation.fromNamespaceAndPath(
            TiedUpMod.MOD_ID,
            "models/obj/blocks/bowl/model.obj"
        );

    public static final ResourceLocation TEXTURE_LOCATION =
        ResourceLocation.fromNamespaceAndPath(
            TiedUpMod.MOD_ID,
            "textures/block/pet_bowl.png"
        );

    /** Whether the bowl currently has food */
    private boolean hasFood = false;

    /** Food saturation level (0-20) */
    private int foodLevel = 0;

    public PetBowlBlockEntity(
        BlockEntityType<?> type,
        BlockPos pos,
        BlockState state
    ) {
        super(type, pos, state);
    }

    @Override
    public ResourceLocation getModelLocation() {
        return MODEL_LOCATION;
    }

    @Override
    public ResourceLocation getTextureLocation() {
        return TEXTURE_LOCATION;
    }

    @Override
    public float getModelScale() {
        return 1.0f; // Adjust based on model size
    }

    // FOOD MANAGEMENT

    public boolean hasFood() {
        return hasFood && foodLevel > 0;
    }

    public int getFoodLevel() {
        return foodLevel;
    }

    /**
     * Fill the bowl with food.
     *
     * @param amount Amount of food to add (saturation points)
     */
    public void fillBowl(int amount) {
        this.foodLevel = Math.min(20, this.foodLevel + amount);
        this.hasFood = this.foodLevel > 0;
        setChanged();
    }

    /**
     * Pet eats from the bowl.
     *
     * @return Amount of food consumed (0 if empty)
     */
    public int eatFromBowl() {
        if (!hasFood()) return 0;

        int consumed = Math.min(4, foodLevel); // Eat up to 4 at a time
        foodLevel -= consumed;
        hasFood = foodLevel > 0;
        setChanged();

        return consumed;
    }

    /**
     * Empty the bowl completely.
     */
    public void emptyBowl() {
        this.foodLevel = 0;
        this.hasFood = false;
        setChanged();
    }

    // NBT

    @Override
    protected void saveAdditional(CompoundTag tag) {
        super.saveAdditional(tag);
        tag.putBoolean("hasFood", hasFood);
        tag.putInt("foodLevel", foodLevel);
    }

    @Override
    public void load(CompoundTag tag) {
        super.load(tag);
        this.hasFood = tag.getBoolean("hasFood");
        this.foodLevel = tag.getInt("foodLevel");
    }
}
