package us.myles.ViaVersion.protocols.protocol1_13to1_12_2.types;

import com.github.steveice10.opennbt.tag.builtin.CompoundTag;
import io.netty.buffer.ByteBuf;
import us.myles.ViaVersion.api.Via;
import us.myles.ViaVersion.api.minecraft.Environment;
import us.myles.ViaVersion.api.minecraft.chunks.BaseChunk;
import us.myles.ViaVersion.api.minecraft.chunks.Chunk;
import us.myles.ViaVersion.api.minecraft.chunks.ChunkSection;
import us.myles.ViaVersion.api.type.PartialType;
import us.myles.ViaVersion.api.type.Type;
import us.myles.ViaVersion.api.type.types.minecraft.BaseChunkType;
import us.myles.ViaVersion.api.type.types.version.Types1_13;
import us.myles.ViaVersion.protocols.protocol1_9_3to1_9_1_2.storage.ClientWorld;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.BitSet;
import java.util.List;
import java.util.logging.Level;

public class Chunk1_13Type extends PartialType<Chunk, ClientWorld> {
    public Chunk1_13Type(ClientWorld param) {
        super(param, Chunk.class);
    }

    @Override
    public Chunk read(ByteBuf input, ClientWorld world) throws Exception {
        int chunkX = input.readInt();
        int chunkZ = input.readInt();

        boolean groundUp = input.readBoolean();
        int primaryBitmask = Type.VAR_INT.read(input);
        ByteBuf data = input.readSlice(Type.VAR_INT.read(input));

        BitSet usedSections = new BitSet(16);
        ChunkSection[] sections = new ChunkSection[16];
        // Calculate section count from bitmask
        for (int i = 0; i < 16; i++) {
            if ((primaryBitmask & (1 << i)) != 0) {
                usedSections.set(i);
            }
        }

        // Read sections
        for (int i = 0; i < 16; i++) {
            if (!usedSections.get(i)) continue; // Section not set
            ChunkSection section = Types1_13.CHUNK_SECTION.read(data);
            sections[i] = section;
            section.readBlockLight(data);
            if (world.getEnvironment() == Environment.NORMAL) {
                section.readSkyLight(data);
            }
        }

        int[] biomeData = groundUp ? new int[256] : null;
        if (groundUp) {
            try {
                for (int i = 0; i < 256; i++) {
                    biomeData[i] = data.readInt();
                }
            } catch (IndexOutOfBoundsException e) {
                // Some plugin isn't sending biome data while groundUp is true, see #1312
                Via.getPlatform().getLogger().log(Level.WARNING, "IndexOutOfBoundsException while trying to read biome data", e);
            }
        }

        List<CompoundTag> nbtData = new ArrayList<>(Arrays.asList(Type.NBT_ARRAY.read(input)));

        // Read all the remaining bytes (workaround for #681)
        if (input.readableBytes() > 0) {
            byte[] array = Type.REMAINING_BYTES.read(input);
            if (Via.getManager().isDebug()) {
                Via.getPlatform().getLogger().warning("Found " + array.length + " more bytes than expected while reading the chunk: " + chunkX + "/" + chunkZ);
            }
        }

        return new BaseChunk(chunkX, chunkZ, groundUp, primaryBitmask, sections, biomeData, nbtData);
    }

    @Override
    public void write(ByteBuf output, ClientWorld world, Chunk chunk) throws Exception {
        output.writeInt(chunk.getX());
        output.writeInt(chunk.getZ());

        output.writeBoolean(chunk.isGroundUp());
        Type.VAR_INT.write(output, chunk.getBitmask());

        ByteBuf buf = output.alloc().buffer();
        try {
            for (int i = 0; i < 16; i++) {
                ChunkSection section = chunk.getSections()[i];
                if (section == null) continue; // Section not set
                Types1_13.CHUNK_SECTION.write(buf, section);
                section.writeBlockLight(buf);

                if (!section.hasSkyLight()) continue; // No sky light, we're done here.
                section.writeSkyLight(buf);

            }
            buf.readerIndex(0);
            Type.VAR_INT.write(output, buf.readableBytes() + (chunk.isBiomeData() ? 256 * 4 : 0));
            output.writeBytes(buf);
        } finally {
            buf.release(); // release buffer
        }

        // Write biome data
        if (chunk.isBiomeData()) {
            for (int value : chunk.getBiomeData()) {
                output.writeInt(value);
            }
        }

        // Write Block Entities
        Type.NBT_ARRAY.write(output, chunk.getBlockEntities().toArray(new CompoundTag[0]));
    }

    @Override
    public Class<? extends Type> getBaseClass() {
        return BaseChunkType.class;
    }
}

@@ -2149,35 +2149,68 @@
 ) %7B%0A            
-try
+if (data.readableBytes() %3E= 256 * 4)
  %7B%0A             
@@ -2331,135 +2331,14 @@
   %7D 
-catch (IndexOutOfBoundsException e) %7B%0A                // Some plugin isn't sending biome data while groundUp is true, see #1312
+else %7B
 %0A   
@@ -2404,54 +2404,59 @@
 G, %22
-IndexOutOfBoundsException while trying to read
+Chunk x=%22+ chunkX + %22 z=%22 + chunkZ + %22 doesn't have
  bio
@@ -2466,12 +2466,10 @@
 data
+!
 %22
-, e
 );%0A 

Use readableBytes