package com.dairymoose.modernlife.tileentities;

import com.dairymoose.entity.DummyEntity;
import com.dairymoose.modernlife.blocks.WinchBlock;
import com.dairymoose.modernlife.blocks.gui.HBlockPos;
import com.dairymoose.modernlife.core.BlockVolume;
import com.dairymoose.modernlife.core.CustomBlocks;
import com.dairymoose.modernlife.core.ModernLifeCommon;
import com.mojang.datafixers.types.Type;
import java.util.HashMap;
import net.minecraft.core.BlockPos;
import net.minecraft.core.Direction;
import net.minecraft.core.NonNullList;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.network.Connection;
import net.minecraft.network.protocol.game.ClientboundBlockEntityDataPacket;
import net.minecraft.sounds.SoundEvents;
import net.minecraft.sounds.SoundSource;
import net.minecraft.world.Container;
import net.minecraft.world.ContainerHelper;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.item.Item;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.item.Items;
import net.minecraft.world.level.ItemLike;
import net.minecraft.world.level.Level;
import net.minecraft.world.level.block.Block;
import net.minecraft.world.level.block.Blocks;
import net.minecraft.world.level.block.ChainBlock;
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.level.block.state.properties.AttachFace;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

/* loaded from: outputsrg.jar:com/dairymoose/modernlife/tileentities/WinchBlockEntity.class */
public class WinchBlockEntity extends BlockEntity implements Container {
    public static final int WINCH_CONTAINER_SIZE = 9;
    private NonNullList<ItemStack> winchStack;
    final int LOOK_FOR_AIR_MAX_TRAVERSAL = 30;
    boolean unpowered;
    public static final BlockEntityType<WinchBlockEntity> WINCH = BlockEntityType.Builder.of(WinchBlockEntity::new, new Block[]{(Block) CustomBlocks.BLOCK_WINCH.get()}).build((Type) null);
    private static final Logger LOGGER = LogManager.getLogger();
    public static HashMap<HBlockPos, DummyEntity> entityForWinchPos = new HashMap<>();
    public static boolean useSmoothAnimation = false;

    public CompoundTag getUpdateTag() {
        CompoundTag nbt = super.getUpdateTag();
        ContainerHelper.saveAllItems(nbt, this.winchStack);
        return nbt;
    }

    public int getMaxStackSize() {
        return 64;
    }

    public boolean canPlaceItem(int flag, ItemStack itemStack) {
        if (isEmpty()) {
            return true;
        }
        return false;
    }

    public void handleUpdateTag(CompoundTag tag) {
        ContainerHelper.loadAllItems(tag, this.winchStack);
        getItem(0);
        super.handleUpdateTag(tag);
    }

    public void load(CompoundTag p_230337_2_) {
        super.load(p_230337_2_);
        ContainerHelper.loadAllItems(p_230337_2_, this.winchStack);
    }

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

    public void onDataPacket(Connection conn, ClientboundBlockEntityDataPacket pkt) {
        CompoundTag tag = pkt.getTag();
        if (tag != null) {
            this.winchStack.clear();
            ContainerHelper.loadAllItems(tag, this.winchStack);
        }
    }

    protected void saveAdditional(CompoundTag p_189515_1_) {
        ContainerHelper.saveAllItems(p_189515_1_, this.winchStack);
    }

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

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

    public int getOpenChainSlot() {
        for (int i = 0; i < this.winchStack.size(); i++) {
            ItemStack itemStack = (ItemStack) this.winchStack.get(i);
            if (itemStack.is(Items.CHAIN) && itemStack.getCount() < itemStack.getMaxStackSize()) {
                return i;
            }
        }
        return getNextFreeSlot();
    }

    public static BlockPos moveAwayFromWinch(BlockState state, BlockPos pos) {
        AttachFace face = state.getValue(WinchBlock.FACE);
        if (face == AttachFace.FLOOR) {
            return pos.above();
        }
        if (face == AttachFace.CEILING) {
            return pos.below();
        }
        return pos.relative(state.getValue(WinchBlock.FACING));
    }

    public static BlockPos moveTowardsWinch(BlockState state, BlockPos pos) {
        AttachFace face = state.getValue(WinchBlock.FACE);
        if (face == AttachFace.FLOOR) {
            return pos.below();
        }
        if (face == AttachFace.CEILING) {
            return pos.above();
        }
        return pos.relative(state.getValue(WinchBlock.FACING).getOpposite());
    }

    public boolean isValidCeilingChain(BlockState posState) {
        if (!posState.is(Blocks.CHAIN)) {
            return false;
        }
        AttachFace face = getBlockState().getValue(WinchBlock.FACE);
        boolean validCeilingChain = (face == AttachFace.CEILING || face == AttachFace.FLOOR) && posState.getValue(ChainBlock.AXIS) == Direction.Axis.Y;
        return validCeilingChain;
    }

    public boolean isValidXChain(BlockState posState) {
        if (!posState.is(Blocks.CHAIN)) {
            return false;
        }
        AttachFace face = getBlockState().getValue(WinchBlock.FACE);
        Direction facing = getBlockState().getValue(WinchBlock.FACING);
        boolean validWallChainX = face == AttachFace.WALL && (facing == Direction.EAST || facing == Direction.WEST) && posState.getValue(ChainBlock.AXIS) == Direction.Axis.X;
        return validWallChainX;
    }

    public boolean isValidZChain(BlockState posState) {
        if (!posState.is(Blocks.CHAIN)) {
            return false;
        }
        AttachFace face = getBlockState().getValue(WinchBlock.FACE);
        Direction facing = getBlockState().getValue(WinchBlock.FACING);
        boolean validWallChainZ = face == AttachFace.WALL && (facing == Direction.NORTH || facing == Direction.SOUTH) && posState.getValue(ChainBlock.AXIS) == Direction.Axis.Z;
        return validWallChainZ;
    }

    public int getTotalChainCount() {
        int sum = 0;
        BlockPos pos = getBlockPos();
        getBlockState().getValue(WinchBlock.FACE);
        BlockPos pos2 = moveAwayFromWinch(getBlockState(), pos);
        BlockState blockState = this.level.getBlockState(pos2);
        while (true) {
            BlockState posState = blockState;
            if (posState.is(Blocks.CHAIN)) {
                if (!isValidCeilingChain(posState) && !isValidXChain(posState) && !isValidZChain(posState)) {
                    return 0;
                }
                sum++;
                pos2 = moveAwayFromWinch(getBlockState(), pos2);
                blockState = this.level.getBlockState(pos2);
            } else {
                return sum;
            }
        }
    }

    public int getInventoryChainCount() {
        int sum = 0;
        for (int i = 0; i < this.winchStack.size(); i++) {
            ItemStack itemStack = (ItemStack) this.winchStack.get(i);
            if (itemStack.is(Items.CHAIN)) {
                sum += itemStack.getCount();
            }
        }
        return sum;
    }

    public int getTotalChainCountIncludingInventory() {
        int sum = getTotalChainCount();
        return sum + getInventoryChainCount();
    }

    public int getNextChainSlot() {
        for (int i = 0; i < this.winchStack.size(); i++) {
            ItemStack itemStack = (ItemStack) this.winchStack.get(i);
            if (itemStack.is(Items.CHAIN)) {
                return i;
            }
        }
        return -1;
    }

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

    public BlockPos getExpandedChainBlockPos() {
        int chainCount = getTotalChainCount();
        if (chainCount == 0) {
            return moveAwayFromWinch(getBlockState(), getBlockPos());
        }
        BlockPos pos = getBlockPos();
        BlockPos pos2 = moveAwayFromWinch(getBlockState(), pos);
        for (int i = 0; i < chainCount; i++) {
            pos2 = moveAwayFromWinch(getBlockState(), pos2);
        }
        return pos2;
    }

    public boolean canExpandChain() {
        int chainCount = getTotalChainCount();
        if (chainCount == 0) {
            return true;
        }
        BlockPos pos = getExpandedChainBlockPos();
        if (this.level.getBlockState(pos).isAir()) {
            return true;
        }
        return false;
    }

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

    public int getContainerSize() {
        return 9;
    }

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

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

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

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

    public void setItem(int var1, ItemStack var2) {
        this.winchStack.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;
    }

    public WinchBlockEntity(BlockPos pos, BlockState state) {
        super(WINCH, pos, state);
        this.winchStack = NonNullList.withSize(9, ItemStack.EMPTY);
        this.LOOK_FOR_AIR_MAX_TRAVERSAL = 30;
        this.unpowered = true;
    }

    public static void tick(Level level, BlockPos pos, BlockState state, WinchBlockEntity entity) {
        entity.tick();
    }

    public void playMovementSound() {
        this.level.playSound((Player) null, getBlockPos(), SoundEvents.CHAIN_STEP, SoundSource.BLOCKS, 0.15f, 0.5f);
    }

    public void tick() {
        int chainSlot;
        int chainCount;
        if (!this.level.isClientSide && ModernLifeCommon.winchTickCounter % 8 == 0) {
            if (((Boolean) getBlockState().getValue(WinchBlock.POWERED)).booleanValue()) {
                int powerLevel = this.level.getBestNeighborSignal(getBlockPos());
                if (powerLevel > 3 && (chainCount = getTotalChainCountIncludingInventory()) > 0) {
                    BlockPos expanded = getExpandedChainBlockPos();
                    ItemStack newChain = new ItemStack(new ItemLike() { // from class: com.dairymoose.modernlife.tileentities.WinchBlockEntity.1
                        C01631() {
                        }

                        public Item asItem() {
                            return Items.CHAIN;
                        }
                    });
                    boolean playedSound = false;
                    BlockPos lastChainLink = moveTowardsWinch(getBlockState(), expanded);
                    BlockState expandedState = this.level.getBlockState(expanded);
                    if (!expandedState.is(CustomBlocks.BLOCK_WINCH_ANCHOR.get()) && !this.level.isClientSide) {
                        for (int i = 0; i < chainCount; i++) {
                            BlockState expandedState2 = this.level.getBlockState(expanded);
                            if (!expandedState2.m_155947_() && !expandedState2.isAir() && expandedState2.getFluidState().isEmpty() && !this.level.getBlockState(lastChainLink).is(CustomBlocks.BLOCK_WINCH.get())) {
                                if (!playedSound) {
                                    playedSound = true;
                                    playMovementSound();
                                    int chainSlot2 = getOpenChainSlot();
                                    if (chainSlot2 != -1) {
                                        ItemStack chainItem = getItem(chainSlot2);
                                        if (chainItem.is(Items.CHAIN)) {
                                            chainItem.grow(1);
                                        } else {
                                            setItem(chainSlot2, newChain);
                                        }
                                    } else {
                                        return;
                                    }
                                }
                                this.level.setBlock(lastChainLink, expandedState2, 2);
                                this.level.setBlock(expanded, Blocks.AIR.defaultBlockState(), 2);
                                this.level.updateNeighborsAt(lastChainLink, this.level.getBlockState(lastChainLink).getBlock());
                                this.level.updateNeighborsAt(expanded, Blocks.AIR);
                                expanded = moveAwayFromWinch(getBlockState(), expanded);
                                lastChainLink = moveAwayFromWinch(getBlockState(), lastChainLink);
                            } else {
                                return;
                            }
                        }
                        return;
                    }
                    if (this.level.isClientSide || this.unpowered) {
                    }
                    BlockVolume bv = new BlockVolume(this.level, expanded, CustomBlocks.BLOCK_WINCH_ANCHOR.get());
                    if (useSmoothAnimation) {
                        if (bv.shiftBlocksWithDummyEntity(this.level, WinchBlockEntity::moveTowardsWinch, getBlockState(), true, this)) {
                            playMovementSound();
                            return;
                        }
                        return;
                    } else {
                        if (bv.shiftBlocks(this.level, WinchBlockEntity::moveTowardsWinch, getBlockState(), true, this)) {
                            playMovementSound();
                            return;
                        }
                        return;
                    }
                }
                return;
            }
            if (getBlockState().getValue(WinchBlock.FACE) == AttachFace.CEILING) {
                if (!this.unpowered) {
                    BlockVolume.shouldFloat = false;
                }
                this.unpowered = true;
                int inventoryChainCount = getInventoryChainCount();
                if (inventoryChainCount > 0) {
                    BlockPos expanded2 = getExpandedChainBlockPos();
                    new ItemStack(new ItemLike() { // from class: com.dairymoose.modernlife.tileentities.WinchBlockEntity.2
                        C01642() {
                        }

                        public Item asItem() {
                            return Items.CHAIN;
                        }
                    });
                    boolean playedSound2 = false;
                    BlockState expandedState3 = this.level.getBlockState(expanded2);
                    if (!expandedState3.is(CustomBlocks.BLOCK_WINCH_ANCHOR.get()) && !this.level.isClientSide) {
                        BlockPos airCheckPos = expanded2;
                        int airCheckCounter = 0;
                        while (!this.level.getBlockState(airCheckPos).isAir()) {
                            airCheckPos = moveAwayFromWinch(getBlockState(), airCheckPos);
                            airCheckCounter++;
                            if (airCheckCounter > 30) {
                                break;
                            }
                        }
                        int blocksMovedCount = 0;
                        if (this.level.getBlockState(airCheckPos).isAir()) {
                            BlockPos source = moveTowardsWinch(getBlockState(), airCheckPos);
                            BlockPos destination = airCheckPos;
                            for (int i2 = 0; i2 < airCheckCounter; i2++) {
                                BlockState sourceState = this.level.getBlockState(source);
                                if (sourceState.m_155947_() || sourceState.isAir() || !sourceState.getFluidState().isEmpty() || this.level.getBlockState(destination).is(CustomBlocks.BLOCK_WINCH.get())) {
                                    break;
                                }
                                if (!playedSound2) {
                                    playedSound2 = true;
                                    playMovementSound();
                                }
                                blocksMovedCount++;
                                this.level.setBlock(destination, sourceState, 2);
                                this.level.setBlock(source, Blocks.AIR.defaultBlockState(), 2);
                                this.level.updateNeighborsAt(destination, this.level.getBlockState(destination).getBlock());
                                this.level.updateNeighborsAt(source, Blocks.AIR);
                                source = moveTowardsWinch(getBlockState(), source);
                                destination = moveTowardsWinch(getBlockState(), destination);
                            }
                        }
                        BlockPos expanded3 = getExpandedChainBlockPos();
                        if (this.level.getBlockState(expanded3).isAir() && blocksMovedCount >= airCheckCounter && (chainSlot = getNextChainSlot()) != -1) {
                            ItemStack itemStack = getItem(chainSlot);
                            itemStack.shrink(1);
                            this.level.setBlock(expanded3, Blocks.CHAIN.defaultBlockState(), 2);
                            return;
                        }
                        return;
                    }
                    boolean shiftResult = new BlockVolume(this.level, expanded2, CustomBlocks.BLOCK_WINCH_ANCHOR.get()).shiftBlocks(this.level, WinchBlockEntity::moveAwayFromWinch, getBlockState(), false, this);
                    BlockPos expanded4 = getExpandedChainBlockPos();
                    if (shiftResult) {
                        this.level.setBlock(expanded4, Blocks.CHAIN.defaultBlockState(), 2);
                        playMovementSound();
                    }
                }
            }
        }
    }

    /* renamed from: com.dairymoose.modernlife.tileentities.WinchBlockEntity$1 */
    /* loaded from: outputsrg.jar:com/dairymoose/modernlife/tileentities/WinchBlockEntity$1.class */
    public class C01631 implements ItemLike {
        C01631() {
        }

        public Item asItem() {
            return Items.CHAIN;
        }
    }

    /* renamed from: com.dairymoose.modernlife.tileentities.WinchBlockEntity$2 */
    /* loaded from: outputsrg.jar:com/dairymoose/modernlife/tileentities/WinchBlockEntity$2.class */
    public class C01642 implements ItemLike {
        C01642() {
        }

        public Item asItem() {
            return Items.CHAIN;
        }
    }
}
