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

import com.dairymoose.modernlife.core.ModernLifeClient;
import com.dairymoose.modernlife.core.ModernLifeCommon;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Supplier;
import net.minecraft.client.Minecraft;
import net.minecraft.core.BlockPos;
import net.minecraft.network.FriendlyByteBuf;
import net.minecraft.network.protocol.Packet;
import net.minecraft.network.protocol.game.ClientGamePacketListener;
import net.minecraft.world.entity.player.Player;
import net.minecraftforge.api.distmarker.Dist;
import net.minecraftforge.fml.loading.FMLEnvironment;
import net.minecraftforge.network.NetworkEvent;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

/* loaded from: outputsrg.jar:com/dairymoose/modernlife/network/play/client/ClientboundMultipartCanvasPacket.class */
public class ClientboundMultipartCanvasPacket implements Packet<ClientGamePacketListener> {
    private long uniqueId;
    private int texWidth;
    private int texHeight;
    private int seqNo;
    private int series;
    private boolean last;
    private byte[] image;
    private BlockPos pos;
    private static final Logger LOGGER = LogManager.getLogger();
    public static AtomicInteger seriesCounter = new AtomicInteger(0);
    private static Map<DualKey, List<ClientboundMultipartCanvasPacket>> cameraPackets = new ConcurrentHashMap();
    private static List<ICanvasReader> updateSubscribers = new CopyOnWriteArrayList();
    private ScheduledExecutorService threadExecutor = Executors.newScheduledThreadPool(3);

    /* loaded from: outputsrg.jar:com/dairymoose/modernlife/network/play/client/ClientboundMultipartCanvasPacket$DualKey.class */
    public static class DualKey {
        public Player player;
        public int series;

        public DualKey(Object player, int series) {
            this.player = (Player) player;
            this.series = series;
        }

        public int hashCode() {
            return 31 + (7 * this.player.hashCode()) + (11 * Integer.hashCode(this.series));
        }

        public boolean equals(Object var1) {
            if (!(var1 instanceof DualKey) || this.player != ((DualKey) var1).player || this.series != ((DualKey) var1).series) {
                return false;
            }
            return true;
        }
    }

    public static void subscribe(ICanvasReader reader) {
        if (reader != null) {
            updateSubscribers.add(reader);
        }
    }

    public static void unsubscribe(ICanvasReader reader) {
        if (reader != null) {
            updateSubscribers.remove(reader);
        }
    }

    public ClientboundMultipartCanvasPacket() {
    }

    public ClientboundMultipartCanvasPacket(int series, long uniqueId, int seqNo, boolean last, byte[] image, int texWidth, int texHeight, BlockPos pos) {
        this.series = series;
        this.uniqueId = uniqueId;
        this.seqNo = seqNo;
        this.last = last;
        this.image = image;
        this.texWidth = texWidth;
        this.texHeight = texHeight;
        this.pos = pos;
    }

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

    public void read(FriendlyByteBuf buffer) {
        this.series = buffer.readInt();
        this.uniqueId = buffer.readLong();
        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.series);
        buffer.writeLong(this.uniqueId);
        buffer.writeInt(this.seqNo);
        buffer.writeBoolean(this.last);
        buffer.writeByteArray(this.image);
        buffer.writeInt(this.texWidth);
        buffer.writeInt(this.texHeight);
        buffer.writeBlockPos(this.pos);
    }

    /* JADX INFO: Access modifiers changed from: package-private */
    /* renamed from: com.dairymoose.modernlife.network.play.client.ClientboundMultipartCanvasPacket$1 */
    /* loaded from: outputsrg.jar:com/dairymoose/modernlife/network/play/client/ClientboundMultipartCanvasPacket$1.class */
    public class RunnableC01331 implements Runnable {
        final /* synthetic */ ClientboundMultipartCanvasPacket val$thisHandler;
        final /* synthetic */ Supplier val$ctx;

        RunnableC01331(ClientboundMultipartCanvasPacket clientboundMultipartCanvasPacket, Supplier supplier) {
            this = clientboundMultipartCanvasPacket;
            ctx = supplier;
        }

        @Override // java.lang.Runnable
        public void run() {
            this.handle((ClientGamePacketListener) ((NetworkEvent.Context) ctx.get()).getNetworkManager().getPacketListener());
        }
    }

    public void handle(Supplier<NetworkEvent.Context> ctx) {
        this.threadExecutor.execute(new Runnable() { // from class: com.dairymoose.modernlife.network.play.client.ClientboundMultipartCanvasPacket.1
            final /* synthetic */ ClientboundMultipartCanvasPacket val$thisHandler;
            final /* synthetic */ Supplier val$ctx;

            RunnableC01331(ClientboundMultipartCanvasPacket this, Supplier ctx2) {
                this = this;
                ctx = ctx2;
            }

            @Override // java.lang.Runnable
            public void run() {
                this.handle((ClientGamePacketListener) ((NetworkEvent.Context) ctx.get()).getNetworkManager().getPacketListener());
            }
        });
        ctx2.get().setPacketHandled(true);
    }

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

    public static boolean ensureDirectory(String subDir) {
        if (StringUtils.isEmpty(subDir)) {
            return false;
        }
        File f = new File(subDir);
        return f.mkdirs();
    }

    public static String getFolderPath() {
        String folderName;
        String root = "";
        String prefix = "";
        if (FMLEnvironment.dist == Dist.CLIENT) {
            prefix = "multiplayer/";
            if (Minecraft.getInstance().hasSingleplayerServer()) {
                prefix = "singleplayer/";
                folderName = Minecraft.getInstance().getSingleplayerServer().m_129910_().getLevelName();
                ModernLifeCommon.LOGGER.debug("currentServer name: " + folderName);
            } else if (Minecraft.getInstance().getCurrentServer() != null) {
                folderName = Minecraft.getInstance().getCurrentServer().name.replaceAll("\\W+", "_").trim();
                if (StringUtils.isEmpty(folderName.replaceAll("_", ""))) {
                    folderName = Minecraft.getInstance().getCurrentServer().ip;
                }
                ModernLifeCommon.LOGGER.debug("getServer name: " + folderName);
            } else {
                folderName = "offline";
            }
        } else {
            folderName = "";
            if (ModernLifeCommon.ServerLevelFolderName != null) {
                root = ModernLifeCommon.ServerLevelFolderName;
            }
        }
        String path = root + "modernlife/" + prefix + folderName;
        if (!path.endsWith("/")) {
            path = path + "/";
        }
        ensureDirectory(path);
        return path;
    }

    public static synchronized void syncHandle(ClientboundMultipartCanvasPacket thisPacket, ClientGamePacketListener p_148833_1_) {
        ModernLifeCommon.LOGGER.debug("Handle ClientboundMultipartCanvasPacket for series = " + thisPacket.series + " with unique ID = " + thisPacket.uniqueId);
        DualKey dk = new DualKey(Minecraft.getInstance().player, thisPacket.series);
        List<ClientboundMultipartCanvasPacket> packets = cameraPackets.get(dk);
        if (packets == null) {
            packets = new ArrayList();
            cameraPackets.put(dk, packets);
        }
        packets.add(thisPacket);
        ClientboundMultipartCanvasPacket lastPacket = thisPacket.getLastPacket(packets);
        byte[] stitchedImage = null;
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        if (lastPacket != null && packets.size() == lastPacket.seqNo) {
            packets.sort(new Comparator<ClientboundMultipartCanvasPacket>() { // from class: com.dairymoose.modernlife.network.play.client.ClientboundMultipartCanvasPacket.2
                C01342() {
                }

                @Override // java.util.Comparator
                public int compare(ClientboundMultipartCanvasPacket var1, ClientboundMultipartCanvasPacket var2) {
                    return var1.seqNo - var2.seqNo;
                }
            });
            for (ClientboundMultipartCanvasPacket 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 + " for series = " + thisPacket.series);
        }
        if (stitchedImage != null && stitchedImage.length != 0) {
            packets.clear();
            ModernLifeCommon.LOGGER.debug("Got image update with ID = " + thisPacket.uniqueId);
            ServerboundMultipartCameraPacket.savePng(thisPacket.uniqueId, stitchedImage, thisPacket.texWidth, thisPacket.texHeight);
            ModernLifeClient.putCachedData(System.currentTimeMillis(), thisPacket.uniqueId, stitchedImage, thisPacket.texWidth, thisPacket.texHeight);
            for (ICanvasReader reader : updateSubscribers) {
                reader.onUpdate(thisPacket.uniqueId);
            }
            return;
        }
        if (stitchedImage != null) {
            packets.clear();
            ModernLifeCommon.LOGGER.debug("incoming image is too big");
        }
    }

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

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

    public void handle(ClientGamePacketListener p_148833_1_) {
        syncHandle(this, p_148833_1_);
    }

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