package com.dairymoose.modernlife.tileentities;

import com.dairymoose.modernlife.blocks.ModernBookshelfBlock;
import com.dairymoose.modernlife.core.CustomBlocks;
import com.dairymoose.modernlife.core.ModernLifeCommon;
import com.mojang.datafixers.types.Type;
import java.util.ArrayList;
import java.util.List;
import net.minecraft.core.BlockPos;
import net.minecraft.core.Direction;
import net.minecraft.core.NonNullList;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.nbt.ListTag;
import net.minecraft.nbt.StringTag;
import net.minecraft.network.Connection;
import net.minecraft.network.protocol.game.ClientboundBlockEntityDataPacket;
import net.minecraft.world.Container;
import net.minecraft.world.ContainerHelper;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.level.block.Block;
import net.minecraft.world.level.block.entity.BlockEntity;
import net.minecraft.world.level.block.entity.BlockEntityType;
import net.minecraft.world.level.block.state.BlockState;
import net.minecraft.world.phys.BlockHitResult;
import net.minecraft.world.phys.HitResult;
import net.minecraft.world.phys.Vec3;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

/* loaded from: outputsrg.jar:com/dairymoose/modernlife/tileentities/ModernBookshelfBlockEntity.class */
public class ModernBookshelfBlockEntity extends BlockEntity implements Container {
    public static final int MODERN_BOOKSHELF_CONTAINER_SIZE = 16;
    private NonNullList<ItemStack> items;
    public NonNullList<String> bookNames;
    public List<Float> bookHeight;
    public int serverSideHitIndex;
    public static final double X_POS_START = 0.0625d;
    public static final double BOOK_WIDTH = 0.1d;
    public static final double BOOK_GAP = 0.01d;
    public static List<String> randomBookNames;
    public static final BlockEntityType<ModernBookshelfBlockEntity> MODERN_BOOKSHELF = BlockEntityType.Builder.of(ModernBookshelfBlockEntity::new, new Block[]{(Block) CustomBlocks.BLOCK_MODERN_ACACIA_BOOKSHELF.get(), (Block) CustomBlocks.BLOCK_MODERN_BIRCH_BOOKSHELF.get(), (Block) CustomBlocks.BLOCK_MODERN_CRIMSON_BOOKSHELF.get(), (Block) CustomBlocks.BLOCK_MODERN_DARK_OAK_BOOKSHELF.get(), (Block) CustomBlocks.BLOCK_MODERN_JUNGLE_BOOKSHELF.get(), (Block) CustomBlocks.BLOCK_MODERN_OAK_BOOKSHELF.get(), (Block) CustomBlocks.BLOCK_MODERN_SPRUCE_BOOKSHELF.get(), (Block) CustomBlocks.BLOCK_MODERN_WARPED_BOOKSHELF.get()}).build((Type) null);
    private static final Logger LOGGER = LogManager.getLogger();
    public static final List<Double> itemPosX = new ArrayList();
    public static final List<Double> itemPosY = new ArrayList();
    public static final List<Double> itemPosZ = new ArrayList();

    static {
        itemPosX.add(Double.valueOf(0.0625d));
        itemPosX.add(Double.valueOf(0.17250000000000001d));
        itemPosX.add(Double.valueOf(0.28250000000000003d));
        itemPosX.add(Double.valueOf(0.39250000000000007d));
        itemPosX.add(Double.valueOf(0.5025000000000001d));
        itemPosX.add(Double.valueOf(0.6125d));
        itemPosX.add(Double.valueOf(0.7225000000000001d));
        itemPosX.add(Double.valueOf(0.8325d));
        itemPosY.add(Double.valueOf(0.0625d));
        itemPosY.add(Double.valueOf(0.0625d));
        itemPosY.add(Double.valueOf(0.0625d));
        itemPosY.add(Double.valueOf(0.0625d));
        itemPosY.add(Double.valueOf(0.0625d));
        itemPosY.add(Double.valueOf(0.0625d));
        itemPosY.add(Double.valueOf(0.0625d));
        itemPosY.add(Double.valueOf(0.0625d));
        itemPosY.add(Double.valueOf(0.53125d));
        itemPosY.add(Double.valueOf(0.53125d));
        itemPosY.add(Double.valueOf(0.53125d));
        itemPosY.add(Double.valueOf(0.53125d));
        itemPosY.add(Double.valueOf(0.53125d));
        itemPosY.add(Double.valueOf(0.53125d));
        itemPosY.add(Double.valueOf(0.53125d));
        itemPosY.add(Double.valueOf(0.53125d));
        itemPosZ.add(Double.valueOf(0.375d));
        randomBookNames = List.of((Object[]) new String[]{"History of Mining", "History of Crafting", "History of Magic", "Ancient History", "Modern Style", "Modern Architecture", "On Building", "On Crafting", "Advanced Building", "Advanced Crafting", "A Brief Respite", "Journey's End", "The Journey", "Heroic Tales", "Feats of Strength", "The Olde Ways", "A Better Tomorrow", "Cobblestone and a Hard Place", "Advanced Swordsmanship", "Expert Swordsmanship", "A Day's Work", "Tending Your Fields", "How To Punch Trees", "The Art of War", "The Odyssey", "Fortune Favors the Bold", "Smithing: A Primer", "The Coldest Night", "The Darkest Night", "Following Your Dreams", "A Cautionary Tale", "Smithing: A Primer", "Lion Of Yesterday", "Agent Of Heaven", "Descendants Of The Gods", "Officers With Gold", "Friends And Enemies", "Mice And Blacksmiths", "Crossbow Of The South", "Obliteration With Sins", "Separated In The Void", "Dead In The Castle", "The Colossal Spider", "Army Of The Eclipse", "Heirs Of The End", "Pirates Of Twilight", "Kings And Invaders", "Gods And Phantoms", "The Living Dead", "The Age Of Heroes", "Breaking The Stars", "Breath Of The West", "Hero Without Direction", "Parrot Of Utopia", "Architect Of Destruction", "Armies Of The Night", "Trees And Knights", "Owls And Heirs", "The Revelation", "Perfection Of The Night", "Crying Out", "Guarded By The North", "Emperor Without Desire", "Hero Without Honor", "Hunters Without Honor", "Friends With Honor", "Mice And Snakes", "Snakes And Spies", "Curse Without Direction", "Fate Of The Void", "Symbols Of The Immortals", "Remembering The Past", "Dog Without Shame", "Invader Without Cause", "The Withered Tree", "Bandits Of The Curse", "Gangsters And Heroes", "Officers And Warriors", "Annihilation Of The Solstice", "Determined To Win", "Running From The End", "Fountain Of Regret", "Tortoise Of Stone", "Warden Of The Prison", "Herald Of The Ancients", "Priests Of The Forest", "Butchers And Guardians", "Kings And Dogs", "Crossbow Of Hope", "Edge Of Dreams", "Vanish In The Commander", "Screams In The Graveyard", "Soldier Of Glory", "Defender Of Greatness", "Swindlers Of The Gods", "Eternal Night", "Creators And Rats", "Climbing The Mountain", "Dreams Of Emeralds", "Dreams Of Diamonds", "Ancient Ruins", "Secrets Revealed", "Painting My Dreams", "Vulture Culture", "Creator Of Silver", "Warriors Of Stone", "Snakes Of The West", "The Long March", "Swindlers And Gods", "Buried Treasure", "Hope And Sorrow", "Bow Of The Forsaken", "Trading In Secrets", "Helping The World", "Parrot Of Wind", "Soldier Of Despair", "Foreigners Without Honor", "Gangsters Of Stone", "Heirs And Knights", "Soldiers and Officers", "History Of Famine", "Goal Of The Ancestors", "Scared Of Nature", "Secrets Of Nature", "Wellspring Of Might", "Forgotten Artifacts", "The Ultimate Folly", "The Hero's Cookbook", "Duchess Of Glory", "Mutiny", "Tools Of The Trade", "Soldiers Without Fear", "Creators And Heroes", "Humans And Vultures", "The Immortals", "Mapping The Kingdom", "Rejecting The King", "Sounds In The Country", "Changeling Of The Night", "Man Of The End", "Turtles With Honor", "Phantoms With Pride", "Warriors And Assassins", "Fish And Officers", "Origin Of Gold", "Vision Of The Forsaken", "Deceiving Myself", "Raiding The Dungeons", "Witch Without Faith", "Hero Without Duty", "Descendants Without Desire", "Rebels Of Time", "Bandits And Lions", "Dogs And Gods", "The Doom That Comes", "Fortune Of The Gods", "Smiles In My Family", "Life In The East", "Bandit Of Fortune", "Hunter With Sins", "The Lucky Bandit", "Owls Of The Plague", "Knights And Spies", "Soldiers And Warriors", "Wand Of Glory", "Man Without A Home", "Screams In Dreams", "Fighting The Power", "Storming The Castle", "The Hidden Dagger", "The Ancient Ways", "True Courage", "True Grit", "True Heroics", "Man Of The Void", "Girls Without Faith", "Swindlers Of Dusk", "Criminals And Kings", "Wizards And Werewolves", "Goal Of The Curse", "Wand Of Nightmares", "Punished By The Darkness", "Force Of The End", "Slave Of The Ocean", "Hunter Of Spring", "Witches Of The Banished", "Ogres Of Dreams", "Women And Pirates", "Creators And Phantoms", "Inspirations And Secrets", "Limit Of The Curse", "Listening To Dreams", "Altering My End", "Throne Of The King", "Rat Of The Prison", "Lords Of Nature", "Mermaids Of The West", "Necromancers And Priests", "Soldiers And Serpents", "Soldier Of Ice", "Hatred Without Fear", "Forsaking The Curse", "Hunted By The Graveyard", "Butcher Of Rainbows", "Human Of Ice", "Birdwatcher", "Owls Of The East", "Thieves And Gods", "Heirs And Protectors", "Influence Of The Eclipse", "Inception", "Never Trust The Champions", "Promises Of The Eternals", "Guilty Damned", "The Final Song", "The Reaping", "Clash in the Sky", "Atlas of Destiny", "Guilty Damned", "A Step Too Far", "History of Villages"});
    }

    public NonNullList<ItemStack> getItems() {
        return this.items;
    }

    public boolean canPlaceItem(int p_18952_, ItemStack p_18953_) {
        return false;
    }

    public int getHitIndex(Player player, HitResult hr) {
        double x;
        double y;
        double z;
        int hitIndex = -1;
        if (hr instanceof BlockHitResult) {
            BlockHitResult bhr = (BlockHitResult) hr;
            BlockPos pos = bhr.getBlockPos();
            BlockState state = getLevel().getBlockState(pos);
            Vec3 hitLocation = bhr.getLocation();
            double leastDistance = 1000.0d;
            if (player.distanceToSqr(hitLocation) <= 6.25d) {
                for (int i = 0; i < 16; i++) {
                    ItemStack itemStack = getItem(i);
                    if (!itemStack.isEmpty()) {
                        double offsetX = itemPosX.get(i % itemPosX.size()).doubleValue() + 0.05d;
                        double offsetY = itemPosY.get(i % itemPosY.size()).doubleValue() + 0.15d;
                        double offsetZ = itemPosZ.get(i % itemPosZ.size()).doubleValue();
                        double x2 = pos.getX();
                        double y2 = pos.getY();
                        double z2 = pos.getZ();
                        if (state.getValue(ModernBookshelfBlock.FACING) == Direction.EAST) {
                            x = x2 + (1.0d - offsetZ);
                            y = y2 + offsetY;
                            z = z2 + (1.0d - offsetX);
                        } else if (state.getValue(ModernBookshelfBlock.FACING) == Direction.NORTH) {
                            x = x2 + (1.0d - offsetX);
                            y = y2 + offsetY;
                            z = z2 + offsetZ;
                        } else if (state.getValue(ModernBookshelfBlock.FACING) == Direction.WEST) {
                            x = x2 + offsetZ;
                            y = y2 + offsetY;
                            z = z2 + offsetX;
                        } else {
                            x = x2 + offsetX;
                            y = y2 + offsetY;
                            z = z2 + (1.0d - offsetZ);
                        }
                        double distSqr = hitLocation.distanceToSqr(new Vec3(x, y, z));
                        double distSqrWithoutY = hitLocation.with(Direction.Axis.Y, 0.0d).distanceToSqr(new Vec3(x, 0.0d, z));
                        double distY = hitLocation.y - y;
                        if (distSqr < leastDistance && distSqrWithoutY <= 0.01d && distY <= 0.15d) {
                            hitIndex = i;
                            leastDistance = distSqr;
                        }
                    }
                }
            }
        }
        return hitIndex;
    }

    public void initItems() {
        BlockEntityType type;
        if (this.items == null && (type = getType()) != null && type == MODERN_BOOKSHELF) {
            ModernLifeCommon.LOGGER.debug("init with size = 16");
            this.items = NonNullList.withSize(16, ItemStack.EMPTY);
            this.bookNames = NonNullList.withSize(16, "");
            this.bookHeight = new ArrayList(16);
            for (int i = 0; i < 16; i++) {
                this.bookHeight.add(Float.valueOf(1.0f));
            }
        }
    }

    public boolean isFull() {
        int count = 0;
        for (int i = 0; i < this.items.size(); i++) {
            if (!((ItemStack) this.items.get(i)).isEmpty()) {
                count++;
            }
        }
        return count == this.items.size();
    }

    public int getNextFreeSlot() {
        for (int i = 0; i < this.items.size(); i++) {
            if (((ItemStack) this.items.get(i)).isEmpty()) {
                return i;
            }
        }
        return -1;
    }

    public int getNextOccupiedSlot() {
        for (int i = this.items.size() - 1; i >= 0; i--) {
            if (!((ItemStack) this.items.get(i)).isEmpty()) {
                return i;
            }
        }
        return -1;
    }

    public void placeItem(ItemStack itemStack) {
        int freeSlot = getNextFreeSlot();
        if (freeSlot != -1) {
            setItem(freeSlot, itemStack.copy());
            float randValue = ((float) Math.random()) * 0.7f;
            float yScale = 0.7f + randValue;
            this.bookHeight.set(freeSlot, Float.valueOf(yScale));
            String displayText = itemStack.getHoverName().getString();
            if (displayText.equals("Book")) {
                displayText = randomBookNames.get((int) (Math.random() * randomBookNames.size()));
            }
            this.bookNames.set(freeSlot, displayText);
        }
    }

    public ModernBookshelfBlockEntity(BlockPos pos, BlockState state) {
        super(MODERN_BOOKSHELF, pos, state);
        this.items = null;
        this.bookNames = null;
        this.serverSideHitIndex = -1;
        initItems();
    }

    public CompoundTag getUpdateTag() {
        CompoundTag nbt = super.getUpdateTag();
        ContainerHelper.saveAllItems(nbt, this.items);
        ListTag list = new ListTag();
        for (int i = 0; i < 16; i++) {
            list.add(StringTag.valueOf((String) this.bookNames.get(i)));
        }
        nbt.put("namelist", list);
        return nbt;
    }

    public void handleUpdateTag(CompoundTag tag) {
        initItems();
        ContainerHelper.loadAllItems(tag, this.items);
        if (tag.contains("namelist")) {
            ListTag list = tag.get("namelist");
            for (int i = 0; i < list.size(); i++) {
                this.bookNames.set(i, list.getString(i));
            }
        }
        super.handleUpdateTag(tag);
    }

    /* renamed from: getUpdatePacket */
    public ClientboundBlockEntityDataPacket m233getUpdatePacket() {
        return ClientboundBlockEntityDataPacket.create(this);
    }

    public void onDataPacket(Connection conn, ClientboundBlockEntityDataPacket pkt) {
        CompoundTag tag = pkt.getTag();
        if (tag != null) {
            initItems();
            this.items.clear();
            ContainerHelper.loadAllItems(tag, this.items);
            if (tag.contains("namelist")) {
                ListTag list = tag.get("namelist");
                for (int i = 0; i < list.size(); i++) {
                    this.bookNames.set(i, list.getString(i));
                }
            }
        }
    }

    public void load(CompoundTag tag) {
        super.load(tag);
        initItems();
        ContainerHelper.loadAllItems(tag, this.items);
        if (tag.contains("namelist")) {
            ListTag list = tag.get("namelist");
            for (int i = 0; i < list.size(); i++) {
                this.bookNames.set(i, list.getString(i));
            }
        }
    }

    protected void saveAdditional(CompoundTag tag) {
        ContainerHelper.saveAllItems(tag, this.items);
        ListTag list = new ListTag();
        for (int i = 0; i < 16; i++) {
            list.add(StringTag.valueOf((String) this.bookNames.get(i)));
        }
        tag.put("namelist", list);
    }

    public void m_6211_() {
        for (int i = 0; i < this.items.size(); i++) {
            this.items.set(i, ItemStack.EMPTY);
        }
    }

    public int getContainerSize() {
        return this.items.size();
    }

    public boolean isEmpty() {
        for (int i = 0; i < this.items.size(); i++) {
            if (this.items.get(i) != ItemStack.EMPTY) {
                return false;
            }
        }
        return true;
    }

    public ItemStack getItem(int var1) {
        return (ItemStack) this.items.get(var1);
    }

    public ItemStack removeItem(int var1, int var2) {
        return ContainerHelper.removeItem(this.items, var1, var2);
    }

    public ItemStack removeItemNoUpdate(int var1) {
        return ContainerHelper.takeItem(this.items, var1);
    }

    public void setItem(int var1, ItemStack var2) {
        this.items.set(var1, var2);
    }

    public boolean stillValid(Player p_70300_1_) {
        return this.level.getBlockEntity(this.worldPosition) == this && p_70300_1_.distanceToSqr(((double) this.worldPosition.getX()) + 0.5d, ((double) this.worldPosition.getY()) + 0.5d, ((double) this.worldPosition.getZ()) + 0.5d) <= 64.0d;
    }
}
