package com.dairymoose.modernlife.network.play.client;

import com.dairymoose.modernlife.blocks.EaselBlock;
import com.dairymoose.modernlife.core.CustomBlocks;
import com.dairymoose.modernlife.core.ModernLifeCommon;
import com.dairymoose.modernlife.core.ModernLifeConfig;
import com.dairymoose.modernlife.tileentities.EaselBlockEntity;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Supplier;
import net.minecraft.core.BlockPos;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.network.FriendlyByteBuf;
import net.minecraft.network.protocol.Packet;
import net.minecraft.network.protocol.game.ServerGamePacketListener;
import net.minecraft.server.level.ServerLevel;
import net.minecraft.server.network.ServerGamePacketListenerImpl;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.level.block.entity.BlockEntity;
import net.minecraft.world.level.block.state.BlockState;
import net.minecraftforge.network.NetworkEvent;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

/* loaded from: outputsrg.jar:com/dairymoose/modernlife/network/play/client/ServerboundMultipartEaselPacket.class */
public class ServerboundMultipartEaselPacket implements Packet<ServerGamePacketListener> {
    private int seqNo;
    private boolean last;
    private byte[] image;
    private int texWidth;
    private int texHeight;
    private BlockPos easelPos;
    private static final Logger LOGGER = LogManager.getLogger();
    private static Map<Player, List<ServerboundMultipartEaselPacket>> canvasPackets = new HashMap();

    public ServerboundMultipartEaselPacket() {
    }

    public ServerboundMultipartEaselPacket(int seqNo, boolean last, byte[] image, int texWidth, int texHeight, BlockPos easelPos) {
        this.seqNo = seqNo;
        this.last = last;
        this.image = image;
        this.texWidth = texWidth;
        this.texHeight = texHeight;
        this.easelPos = easelPos;
    }

    public ServerboundMultipartEaselPacket(FriendlyByteBuf buffer) {
        read(buffer);
    }

    public void read(FriendlyByteBuf buffer) {
        this.seqNo = buffer.readInt();
        this.last = buffer.readBoolean();
        this.image = buffer.readByteArray();
        this.texWidth = buffer.readInt();
        this.texHeight = buffer.readInt();
        this.easelPos = buffer.readBlockPos();
    }

    public void write(FriendlyByteBuf buffer) {
        buffer.writeInt(this.seqNo);
        buffer.writeBoolean(this.last);
        buffer.writeByteArray(this.image);
        buffer.writeInt(this.texWidth);
        buffer.writeInt(this.texHeight);
        buffer.writeBlockPos(this.easelPos);
    }

    public void handle(Supplier<NetworkEvent.Context> ctx) {
        ctx.get().enqueueWork(() -> {
            ((NetworkEvent.Context) ctx.get()).getSender();
            handle((ServerGamePacketListener) ((NetworkEvent.Context) ctx.get()).getNetworkManager().getPacketListener());
        });
        ctx.get().setPacketHandled(true);
    }

    private ServerboundMultipartEaselPacket getLastPacket(List<ServerboundMultipartEaselPacket> packets) {
        for (ServerboundMultipartEaselPacket packet : packets) {
            if (packet.last) {
                return packet;
            }
        }
        return null;
    }

    public void handle(ServerGamePacketListener p_148833_1_) {
        ModernLifeCommon.LOGGER.debug("Handle CMultipartCanvasPacket");
        if (this.easelPos != null && (p_148833_1_ instanceof ServerGamePacketListenerImpl)) {
            ServerGamePacketListenerImpl serverHandler = (ServerGamePacketListenerImpl) p_148833_1_;
            new CompoundTag();
            ServerLevel level = serverHandler.player.getLevel();
            ModernLifeCommon.LOGGER.debug("world = " + level);
            if (level != null && level.isLoaded(this.easelPos)) {
                BlockState easelState = level.getBlockState(this.easelPos);
                ModernLifeCommon.LOGGER.debug("easelState = " + easelState);
                if (easelState != null && easelState.is(CustomBlocks.BLOCK_EASEL.get()) && !((Boolean) easelState.getValue(EaselBlock.EMPTY)).booleanValue()) {
                    List<ServerboundMultipartEaselPacket> packets = canvasPackets.get(serverHandler.player);
                    if (packets == null) {
                        packets = new ArrayList();
                        canvasPackets.put(serverHandler.player, packets);
                    }
                    packets.add(this);
                    ServerboundMultipartEaselPacket lastPacket = getLastPacket(packets);
                    byte[] stitchedImage = null;
                    ByteArrayOutputStream stream = new ByteArrayOutputStream();
                    ModernLifeCommon.LOGGER.debug("packets.size = " + packets.size() + ", lastPacket = " + lastPacket);
                    if (lastPacket != null && packets.size() == lastPacket.seqNo) {
                        packets.sort(new Comparator<ServerboundMultipartEaselPacket>() { // from class: com.dairymoose.modernlife.network.play.client.ServerboundMultipartEaselPacket.1
                            C01391() {
                            }

                            @Override // java.util.Comparator
                            public int compare(ServerboundMultipartEaselPacket var1, ServerboundMultipartEaselPacket var2) {
                                return var1.seqNo - var2.seqNo;
                            }
                        });
                        for (ServerboundMultipartEaselPacket packet : packets) {
                            try {
                                stream.write(packet.image);
                            } catch (IOException e) {
                                ModernLifeCommon.LOGGER.debug("error writing image part", e);
                            }
                        }
                        stitchedImage = stream.toByteArray();
                    }
                    if (stitchedImage != null) {
                        ModernLifeCommon.LOGGER.debug("image length = " + stitchedImage.length);
                    }
                    int maxTexSizeW = 512;
                    int maxTexSizeH = 512;
                    Integer configIntW = (Integer) ModernLifeConfig.COMMON.cameraResolutionW.get();
                    Integer configIntH = (Integer) ModernLifeConfig.COMMON.cameraResolutionH.get();
                    if (configIntW != null) {
                        maxTexSizeW = configIntW.intValue();
                    }
                    if (configIntH != null) {
                        maxTexSizeH = configIntH.intValue();
                    }
                    if (stitchedImage != null && stitchedImage.length != 0 && stitchedImage.length <= ServerboundMultipartCameraPacket.MAX_IMAGE_LENGTH(maxTexSizeW) && this.texWidth <= maxTexSizeW && this.texHeight <= maxTexSizeH) {
                        packets.clear();
                        ModernLifeCommon.LOGGER.debug("easelPos = " + this.easelPos);
                        BlockEntity tileEntity = level.getChunkAt(this.easelPos).getBlockEntity(this.easelPos);
                        ModernLifeCommon.LOGGER.debug("tileEntity = " + tileEntity);
                        if (tileEntity instanceof EaselBlockEntity) {
                            EaselBlockEntity easelBlockEntity = (EaselBlockEntity) tileEntity;
                            ItemStack currentItem = easelBlockEntity.getItem(0).copy();
                            if (easelBlockEntity != null) {
                                level.setBlockAndUpdate(this.easelPos, (BlockState) easelState.setValue(EaselBlock.EMPTY, true));
                                int texSize = 64;
                                if (this.texWidth > 0) {
                                }
                                long uniqueId = 0;
                                if (currentItem.getTag() != null && currentItem.getTag().contains("UniqueId")) {
                                    uniqueId = currentItem.getTag().getLong("UniqueId");
                                }
                                if (currentItem.getTag() != null && currentItem.getTag().contains("TextureSize")) {
                                    texSize = currentItem.getTag().getInt("TextureSize");
                                    this.texWidth = currentItem.getTag().getInt("TextureWidth");
                                    this.texHeight = currentItem.getTag().getInt("TextureHeight");
                                }
                                if (uniqueId == 0) {
                                    uniqueId = ModernLifeCommon.getNextCanvasId();
                                }
                                ServerboundMultipartCameraPacket.savePng(uniqueId, stitchedImage, this.texWidth, this.texHeight);
                                currentItem.getOrCreateTag().putLong("UniqueId", uniqueId);
                                currentItem.getOrCreateTag().putInt("TextureSize", texSize);
                                currentItem.getOrCreateTag().putInt("TextureWidth", this.texWidth);
                                currentItem.getOrCreateTag().putInt("TextureHeight", this.texHeight);
                                serverHandler.player.addItem(currentItem);
                                easelBlockEntity.setItem(0, ItemStack.EMPTY);
                                ServerboundMultipartCameraPacket.pushImageUpdate(currentItem);
                                return;
                            }
                            return;
                        }
                        return;
                    }
                    if (stitchedImage != null) {
                        packets.clear();
                        ModernLifeCommon.LOGGER.error("incoming image (" + this.texWidth + "/" + this.texHeight + "/" + maxTexSizeW + "/" + maxTexSizeH + ") is too big: " + stitchedImage.length + "/" + ServerboundMultipartCameraPacket.MAX_IMAGE_LENGTH(maxTexSizeW));
                    }
                }
            }
        }
    }

    /* renamed from: com.dairymoose.modernlife.network.play.client.ServerboundMultipartEaselPacket$1 */
    /* loaded from: outputsrg.jar:com/dairymoose/modernlife/network/play/client/ServerboundMultipartEaselPacket$1.class */
    public class C01391 implements Comparator<ServerboundMultipartEaselPacket> {
        C01391() {
        }

        @Override // java.util.Comparator
        public int compare(ServerboundMultipartEaselPacket var1, ServerboundMultipartEaselPacket var2) {
            return var1.seqNo - var2.seqNo;
        }
    }

    public byte[] getImage() {
        return this.image;
    }
}
