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

import com.dairymoose.modernlife.core.CustomBlocks;
import com.dairymoose.modernlife.core.ModernLifeCommon;
import com.dairymoose.modernlife.core.ModernLifeConfig;
import com.dairymoose.modernlife.core.ModernLifeNetwork;
import com.dairymoose.modernlife.util.CanvasData;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
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.Random;
import java.util.concurrent.locks.ReentrantLock;
import java.util.function.Supplier;
import javax.imageio.ImageIO;
import javax.imageio.metadata.IIOInvalidTreeException;
import javax.imageio.metadata.IIOMetadata;
import javax.imageio.metadata.IIOMetadataNode;
import net.minecraft.core.BlockPos;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.nbt.ListTag;
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.level.ServerPlayer;
import net.minecraft.server.network.ServerGamePacketListenerImpl;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.item.Item;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.level.ItemLike;
import net.minecraftforge.network.NetworkEvent;
import net.minecraftforge.network.PacketDistributor;
import org.apache.commons.io.FileUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

/* loaded from: outputsrg.jar:com/dairymoose/modernlife/network/play/client/ServerboundMultipartCameraPacket.class */
public class ServerboundMultipartCameraPacket implements Packet<ServerGamePacketListener> {
    private int texWidth;
    private int texHeight;
    private int seqNo;
    private boolean last;
    private byte[] image;
    private boolean provideInstantCanvas = false;
    private static final Logger LOGGER = LogManager.getLogger();
    private static long lastPacketTimestamp = 0;
    private static int incomingPacketCounter = 0;
    private static long reenableCamera = 0;
    private static Map<Player, List<ServerboundMultipartCameraPacket>> cameraPackets = new HashMap();
    public static Map<Long, CanvasHashCodeData> canvasHashCodes = new HashMap();
    private static ReentrantLock pngMutex = new ReentrantLock();

    /* loaded from: outputsrg.jar:com/dairymoose/modernlife/network/play/client/ServerboundMultipartCameraPacket$CanvasHashCodeData.class */
    public static class CanvasHashCodeData {
        Integer hashCode;
        long timestamp;
    }

    /* loaded from: outputsrg.jar:com/dairymoose/modernlife/network/play/client/ServerboundMultipartCameraPacket$PngSizeHolder.class */
    public static class PngSizeHolder {
        public int width;
        public int height;
    }

    public static int MAX_IMAGE_LENGTH(int textureSize) {
        return textureSize * textureSize * 3;
    }

    public ServerboundMultipartCameraPacket() {
    }

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

    public ServerboundMultipartCameraPacket(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();
    }

    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);
    }

    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 ServerboundMultipartCameraPacket getLastPacket(List<ServerboundMultipartCameraPacket> packets) {
        for (ServerboundMultipartCameraPacket packet : packets) {
            if (packet.last) {
                return packet;
            }
        }
        return null;
    }

    public static void pushImageUpdate(long uniqueId, ServerPlayer player) {
        PngSizeHolder sizeHolder = new PngSizeHolder();
        byte[] compressed = loadPng(uniqueId, sizeHolder);
        CanvasHashCodeData chcd = new CanvasHashCodeData();
        chcd.hashCode = Integer.valueOf(ModernLifeCommon.getHashCodeForBytes(compressed));
        chcd.timestamp = System.currentTimeMillis();
        canvasHashCodes.put(Long.valueOf(uniqueId), chcd);
        if (compressed != null) {
            List<byte[]> parts = new ArrayList<>();
            for (int i = 0; i < Math.ceil(compressed.length / 30000); i++) {
                ByteArrayOutputStream stream = new ByteArrayOutputStream();
                int startIndex = i * 30000;
                int bytesToWrite = Math.min(compressed.length - startIndex, 30000);
                stream.write(compressed, startIndex, bytesToWrite);
                byte[] part = stream.toByteArray();
                parts.add(part);
            }
            int series = ClientboundMultipartCanvasPacket.seriesCounter.incrementAndGet();
            for (int i2 = 0; i2 < parts.size(); i2++) {
                int seqNo = i2 + 1;
                boolean last = false;
                if (seqNo == parts.size()) {
                    last = true;
                }
                PacketDistributor.PacketTarget target = PacketDistributor.ALL.noArg();
                if (player != null) {
                    target = PacketDistributor.PLAYER.with(() -> {
                        return player;
                    });
                }
                ModernLifeNetwork.INSTANCE.send(target, new ClientboundMultipartCanvasPacket(series, uniqueId, seqNo, last, parts.get(i2), sizeHolder.width, sizeHolder.height, new BlockPos(1, 1, 1)));
            }
            return;
        }
        ModernLifeCommon.LOGGER.error("Failed to get updateTag png for ID=" + uniqueId);
    }

    public static void pushImageUpdate(ItemStack itemStack) {
        if (itemStack.getTag() != null && itemStack.getTag().contains("UniqueId")) {
            long uniqueId = itemStack.getTag().getLong("UniqueId");
            pushImageUpdate(uniqueId, null);
        }
    }

    public static String getSubFolderPrepend() {
        String folderName = ClientboundMultipartCanvasPacket.getFolderPath();
        String subFolder = "";
        if (folderName != null) {
            subFolder = folderName;
            if (!subFolder.endsWith("/")) {
                subFolder = subFolder + "/";
            }
        }
        return subFolder;
    }

    private static void addTextEntry(IIOMetadata metadata, String key, String value) throws IIOInvalidTreeException {
        IIOMetadataNode textEntry = new IIOMetadataNode("TextEntry");
        textEntry.setAttribute("keyword", key);
        textEntry.setAttribute("value", value);
        IIOMetadataNode text = new IIOMetadataNode("Text");
        text.appendChild(textEntry);
        IIOMetadataNode root = new IIOMetadataNode("javax_imageio_1.0");
        root.appendChild(text);
        metadata.mergeTree("javax_imageio_1.0", root);
    }

    public static void savePng(long uniqueId, byte[] stitchedImage, int w, int h) {
        BufferedImage bufferedImage = new BufferedImage(w, h, 1);
        CanvasData canvasData = new CanvasData();
        canvasData.setTextureSize(w, h);
        canvasData.fromCompressedNbt(stitchedImage);
        for (int x = 0; x < w; x++) {
            for (int y = 0; y < h; y++) {
                int rgbPixel = canvasData.getRgbPixel(x, y);
                bufferedImage.setRGB(x, y, rgbPixel);
            }
        }
        String subFolder = getSubFolderPrepend();
        ModernLifeCommon.LOGGER.debug("save to: " + subFolder);
        File outputFile = new File(subFolder + "canvas" + uniqueId + ".png");
        try {
            try {
                pngMutex.lock();
                ImageIO.write(bufferedImage, "png", outputFile);
                pngMutex.unlock();
            } catch (IOException e) {
                ModernLifeCommon.LOGGER.error("Error saving stitched image to disk with ID=" + uniqueId, e);
                pngMutex.unlock();
            }
        } catch (Throwable th) {
            pngMutex.unlock();
            throw th;
        }
    }

    public static long copyPng(long uniqueId) {
        String subFolder = getSubFolderPrepend();
        long nextUniqueId = ModernLifeCommon.getNextCanvasId();
        File inputFile = new File(subFolder + "canvas" + uniqueId + ".png");
        File outputFile = new File(subFolder + "canvas" + nextUniqueId + ".png");
        if (inputFile.exists()) {
            try {
                FileUtils.copyFile(inputFile, outputFile);
                return nextUniqueId;
            } catch (IOException e) {
                ModernLifeCommon.LOGGER.error("Failed to copy file: " + inputFile + " to: " + outputFile);
                return -1L;
            }
        }
        return -1L;
    }

    public static boolean deletePng(long uniqueId) {
        String subFolder = getSubFolderPrepend();
        File inputFile = new File(subFolder + "canvas" + uniqueId + ".png");
        if (inputFile.exists()) {
            return inputFile.delete();
        }
        return false;
    }

    public static byte[] loadPng(long uniqueId, PngSizeHolder sizeHolder) {
        if (sizeHolder == null) {
            return null;
        }
        String subFolder = getSubFolderPrepend();
        File inputFile = new File(subFolder + "canvas" + uniqueId + ".png");
        BufferedImage image = null;
        try {
            if (inputFile.exists()) {
                try {
                    pngMutex.lock();
                    image = ImageIO.read(inputFile);
                    pngMutex.unlock();
                } catch (IOException e) {
                    ModernLifeCommon.LOGGER.error("Error reading saved png from disk with ID=" + uniqueId);
                    pngMutex.unlock();
                }
            } else {
                ModernLifeCommon.LOGGER.error("Canvas png did not exist for unique ID=" + uniqueId);
            }
            if (image != null) {
                sizeHolder.width = image.getWidth();
                sizeHolder.height = image.getHeight();
                return toCanvasDataFromPng(image);
            }
            return null;
        } catch (Throwable th) {
            pngMutex.unlock();
            throw th;
        }
    }

    public static byte[] toCanvasDataFromPng(BufferedImage bufferedImage) {
        if (bufferedImage == null) {
            ModernLifeCommon.LOGGER.error("bufferedImage was null");
            return null;
        }
        if (bufferedImage.getWidth() <= 0 || bufferedImage.getHeight() <= 0) {
            ModernLifeCommon.LOGGER.error("Unexpected image size");
            return null;
        }
        int maxVal = 2048;
        Integer configInt = (Integer) ModernLifeConfig.SERVER.maxImageSizePixels.get();
        if (configInt != null) {
            maxVal = configInt.intValue();
        }
        if (bufferedImage.getWidth() > maxVal || bufferedImage.getHeight() > maxVal) {
            ModernLifeCommon.LOGGER.error("Image dimensions are too large");
            return null;
        }
        CanvasData canvasData = new CanvasData();
        canvasData.setTextureSize(bufferedImage.getWidth(), bufferedImage.getHeight());
        canvasData.initImage();
        ModernLifeCommon.LOGGER.debug("width = " + bufferedImage.getWidth());
        ModernLifeCommon.LOGGER.debug("height = " + bufferedImage.getHeight());
        ModernLifeCommon.LOGGER.debug("type = " + bufferedImage.getType());
        for (int x = 0; x < bufferedImage.getWidth(); x++) {
            for (int y = 0; y < bufferedImage.getHeight(); y++) {
                int rgb = bufferedImage.getRGB(x, y);
                canvasData.setRgbPixel(x, y, rgb);
            }
        }
        return canvasData.toCompressedNbt();
    }

    public void handle(ServerGamePacketListener p_148833_1_) {
        ListTag imageList;
        ModernLifeCommon.LOGGER.debug("Handle ServerboundMultipartCameraPacket");
        if (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) {
                List<ServerboundMultipartCameraPacket> packets = cameraPackets.get(serverHandler.player);
                if (packets == null) {
                    packets = new ArrayList();
                    cameraPackets.put(serverHandler.player, packets);
                }
                packets.add(this);
                ServerboundMultipartCameraPacket lastPacket = getLastPacket(packets);
                byte[] stitchedImage = null;
                ByteArrayOutputStream stream = new ByteArrayOutputStream();
                if (lastPacket != null && packets.size() == lastPacket.seqNo) {
                    packets.sort(new Comparator<ServerboundMultipartCameraPacket>() { // from class: com.dairymoose.modernlife.network.play.client.ServerboundMultipartCameraPacket.1
                        C01371() {
                        }

                        @Override // java.util.Comparator
                        public int compare(ServerboundMultipartCameraPacket var1, ServerboundMultipartCameraPacket var2) {
                            return var1.seqNo - var2.seqNo;
                        }
                    });
                    for (ServerboundMultipartCameraPacket 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 <= MAX_IMAGE_LENGTH(maxTexSizeW) && this.texWidth <= maxTexSizeW && this.texHeight <= maxTexSizeH) {
                    packets.clear();
                    long currentTimestamp = System.currentTimeMillis();
                    long j = currentTimestamp - lastPacketTimestamp;
                    long timeDiffReenableCamera = currentTimestamp - reenableCamera;
                    if (timeDiffReenableCamera >= 0) {
                        if (this.provideInstantCanvas) {
                            ItemStack itemStack = new ItemStack(new ItemLike() { // from class: com.dairymoose.modernlife.network.play.client.ServerboundMultipartCameraPacket.2
                                C01382() {
                                }

                                public Item asItem() {
                                    return CustomBlocks.ITEM_CANVAS.get();
                                }
                            });
                            long uniqueId = ModernLifeCommon.getNextCanvasId();
                            itemStack.getOrCreateTag().putLong("UniqueId", uniqueId);
                            savePng(uniqueId, stitchedImage, this.texWidth, this.texHeight);
                            if (this.texWidth > 0) {
                                itemStack.getTag().putInt("TextureSize", this.texWidth);
                                itemStack.getTag().putInt("TextureWidth", this.texWidth);
                                itemStack.getTag().putInt("TextureHeight", this.texHeight);
                            }
                            serverHandler.player.addItem(itemStack);
                            return;
                        }
                        ItemStack itemStack2 = serverHandler.player.getMainHandItem();
                        if (itemStack2.getItem() == CustomBlocks.ITEM_CAMERA.get() && itemStack2.getDamageValue() < itemStack2.getMaxDamage()) {
                            ListTag listTag = itemStack2.getOrCreateTag().get("ImageList");
                            if (listTag instanceof ListTag) {
                                imageList = listTag;
                            } else {
                                imageList = new ListTag();
                            }
                            CompoundTag imageNbt = new CompoundTag();
                            long uniqueId2 = ModernLifeCommon.getNextCanvasId();
                            savePng(uniqueId2, stitchedImage, this.texWidth, this.texHeight);
                            imageNbt.putLong("UniqueId", uniqueId2);
                            imageList.add(imageNbt);
                            itemStack2.getOrCreateTag().put("ImageList", imageList);
                            if (this.texWidth > 0) {
                                itemStack2.getTag().putInt("TextureSize", this.texWidth);
                                itemStack2.getTag().putInt("TextureWidth", this.texWidth);
                                itemStack2.getTag().putInt("TextureHeight", this.texHeight);
                            }
                            itemStack2.hurt(1, new Random(), (ServerPlayer) null);
                            pushImageUpdate(uniqueId2, serverHandler.player);
                            return;
                        }
                        return;
                    }
                    return;
                }
                if (stitchedImage != null) {
                    packets.clear();
                    ModernLifeCommon.LOGGER.error("incoming image (" + this.texWidth + "/" + this.texHeight + "/" + maxTexSizeW + "/" + maxTexSizeH + ") is too big: " + stitchedImage.length + "/" + MAX_IMAGE_LENGTH(maxTexSizeW));
                }
            }
        }
    }

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

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

    /* renamed from: com.dairymoose.modernlife.network.play.client.ServerboundMultipartCameraPacket$2 */
    /* loaded from: outputsrg.jar:com/dairymoose/modernlife/network/play/client/ServerboundMultipartCameraPacket$2.class */
    public class C01382 implements ItemLike {
        C01382() {
        }

        public Item asItem() {
            return CustomBlocks.ITEM_CANVAS.get();
        }
    }

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