package jesse.keeblarcraft.Entities;

import jesse.keeblarcraft.GuiMgr.ShopKeeper.ShopKeeperHandler;
import net.minecraft.entity.EntityType;
import net.minecraft.entity.passive.VillagerEntity;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.screen.SimpleNamedScreenHandlerFactory;
import net.minecraft.text.Text;
import net.minecraft.util.ActionResult;
import net.minecraft.util.Hand;
import net.minecraft.village.TradeOffer;
import net.minecraft.village.TradeOfferList;
import net.minecraft.world.World;

import java.util.OptionalInt;

public class ShopKeeper extends VillagerEntity {
    private final int MAX_STORE_ITEMS = 64; // TODO: May be in wrong area. Number will be QA tested from scrolling amount

    public ShopKeeper(EntityType<? extends VillagerEntity> entityType, World world) {
        super(entityType, world);
    }

    @Override
    public ActionResult interactMob(PlayerEntity player, Hand hand) {
        BeginTrades(player);
        return ActionResult.success(this.getWorld().isClient());
    }

    private void BeginTrades(PlayerEntity player) {
        System.out.println("Beginning trades with player");
        super.setCustomer(player);
        this.sendOffers(player, this.getDisplayName(), this.getVillagerData().getLevel());
    }

    @Override
    public void sendOffers(PlayerEntity player, Text name, int levelProgress) {
        OptionalInt optInt = player.openHandledScreen(
                new SimpleNamedScreenHandlerFactory((syncId, playerInventory, playerx) ->
                        new ShopKeeperHandler(syncId, playerInventory, this), name)
        );

        if (optInt.isPresent()) {
            TradeOfferList offers = this.getOffers();
            if (!offers.isEmpty()) {
                player.sendTradeOffers(optInt.getAsInt(), offers, levelProgress, this.getExperience(), this.isLeveledMerchant(), this.canRefreshTrades());
            }
        }
    }

    // Shop Keepers do not breed!
    @Override
    public boolean canBreed() {
        return false;
    }

    @Override
    protected Text getDefaultName() {
        return Text.of("Shop Keeper");
    }

    @Override
    protected void afterUsing(TradeOffer offer) {
        System.out.println("After using called");
    }

    // Get the offer list upon opening handled screen if valid
    @Override
    public TradeOfferList getOffers() {
        if (this.offers == null) {
            this.offers = new TradeOfferList();
            this.fillRecipes();
        }

        return this.offers;
    }

    @Override
    public boolean canSummonGolem(long time) {
        return false;
    }
}
