// 
// Decompiled by Procyon v0.6.0
// 

package com.hypixel.hytale.protocol;

import java.util.Arrays;
import com.hypixel.hytale.protocol.io.ValidationResult;
import java.util.Iterator;
import com.hypixel.hytale.protocol.io.PacketIO;
import java.util.HashMap;
import com.hypixel.hytale.protocol.io.ProtocolException;
import com.hypixel.hytale.protocol.io.VarInt;
import io.netty.buffer.ByteBuf;
import javax.annotation.Nonnull;
import java.util.Map;
import javax.annotation.Nullable;

public class ItemLibrary
{
    public static final int NULLABLE_BIT_FIELD_SIZE = 1;
    public static final int FIXED_BLOCK_SIZE = 1;
    public static final int VARIABLE_FIELD_COUNT = 2;
    public static final int VARIABLE_BLOCK_START = 9;
    public static final int MAX_SIZE = 1677721600;
    @Nullable
    public ItemBase[] items;
    @Nullable
    public Map<Integer, String>[] blockMap;
    
    public ItemLibrary() {
    }
    
    public ItemLibrary(@Nullable final ItemBase[] items, @Nullable final Map<Integer, String>[] blockMap) {
        this.items = items;
        this.blockMap = blockMap;
    }
    
    public ItemLibrary(@Nonnull final ItemLibrary other) {
        this.items = other.items;
        this.blockMap = other.blockMap;
    }
    
    @Nonnull
    public static ItemLibrary deserialize(@Nonnull final ByteBuf buf, final int offset) {
        final ItemLibrary obj = new ItemLibrary();
        final byte nullBits = buf.getByte(offset);
        if ((nullBits & 0x1) != 0x0) {
            final int varPos0 = offset + 9 + buf.getIntLE(offset + 1);
            final int itemsCount = VarInt.peek(buf, varPos0);
            if (itemsCount < 0) {
                throw ProtocolException.negativeLength("Items", itemsCount);
            }
            if (itemsCount > 4096000) {
                throw ProtocolException.arrayTooLong("Items", itemsCount, 4096000);
            }
            final int varIntLen = VarInt.length(buf, varPos0);
            if (varPos0 + varIntLen + itemsCount * 147L > buf.readableBytes()) {
                throw ProtocolException.bufferTooSmall("Items", varPos0 + varIntLen + itemsCount * 147, buf.readableBytes());
            }
            obj.items = new ItemBase[itemsCount];
            int elemPos = varPos0 + varIntLen;
            for (int i = 0; i < itemsCount; ++i) {
                obj.items[i] = ItemBase.deserialize(buf, elemPos);
                elemPos += ItemBase.computeBytesConsumed(buf, elemPos);
            }
        }
        if ((nullBits & 0x2) != 0x0) {
            final int varPos2 = offset + 9 + buf.getIntLE(offset + 5);
            final int blockMapCount = VarInt.peek(buf, varPos2);
            if (blockMapCount < 0) {
                throw ProtocolException.negativeLength("BlockMap", blockMapCount);
            }
            if (blockMapCount > 4096000) {
                throw ProtocolException.arrayTooLong("BlockMap", blockMapCount, 4096000);
            }
            final int varIntLen = VarInt.length(buf, varPos2);
            final Map<Integer, String>[] blockMapArr = new Map[blockMapCount];
            obj.blockMap = blockMapArr;
            int elemPos2 = varPos2 + varIntLen;
            for (int j = 0; j < blockMapCount; ++j) {
                final int mapLen = VarInt.peek(buf, elemPos2);
                final int mapVarLen = VarInt.length(buf, elemPos2);
                final HashMap<Integer, String> map = new HashMap<Integer, String>(mapLen);
                int mapPos = elemPos2 + mapVarLen;
                for (int k = 0; k < mapLen; ++k) {
                    final int key = buf.getIntLE(mapPos);
                    mapPos += 4;
                    final int valLen = VarInt.peek(buf, mapPos);
                    if (valLen < 0) {
                        throw ProtocolException.negativeLength("val", valLen);
                    }
                    if (valLen > 4096000) {
                        throw ProtocolException.stringTooLong("val", valLen, 4096000);
                    }
                    final int valVarLen = VarInt.length(buf, mapPos);
                    final String val = PacketIO.readVarString(buf, mapPos);
                    mapPos += valVarLen + valLen;
                    if (map.put(key, val) != null) {
                        throw ProtocolException.duplicateKey("BlockMap[" + j, (Object)key);
                    }
                }
                obj.blockMap[j] = map;
                elemPos2 = mapPos;
            }
        }
        return obj;
    }
    
    public static int computeBytesConsumed(@Nonnull final ByteBuf buf, final int offset) {
        final byte nullBits = buf.getByte(offset);
        int maxEnd = 9;
        if ((nullBits & 0x1) != 0x0) {
            final int fieldOffset0 = buf.getIntLE(offset + 1);
            int pos0 = offset + 9 + fieldOffset0;
            final int arrLen = VarInt.peek(buf, pos0);
            pos0 += VarInt.length(buf, pos0);
            for (int i = 0; i < arrLen; ++i) {
                pos0 += ItemBase.computeBytesConsumed(buf, pos0);
            }
            if (pos0 - offset > maxEnd) {
                maxEnd = pos0 - offset;
            }
        }
        if ((nullBits & 0x2) != 0x0) {
            final int fieldOffset2 = buf.getIntLE(offset + 5);
            int pos2 = offset + 9 + fieldOffset2;
            final int arrLen = VarInt.peek(buf, pos2);
            pos2 += VarInt.length(buf, pos2);
            for (int i = 0; i < arrLen; ++i) {
                final int dictLen = VarInt.peek(buf, pos2);
                pos2 += VarInt.length(buf, pos2);
                for (int j = 0; j < dictLen; ++j) {
                    pos2 += 4;
                    final int sl = VarInt.peek(buf, pos2);
                    pos2 += VarInt.length(buf, pos2) + sl;
                }
            }
            if (pos2 - offset > maxEnd) {
                maxEnd = pos2 - offset;
            }
        }
        return maxEnd;
    }
    
    public void serialize(@Nonnull final ByteBuf buf) {
        final int startPos = buf.writerIndex();
        byte nullBits = 0;
        if (this.items != null) {
            nullBits |= 0x1;
        }
        if (this.blockMap != null) {
            nullBits |= 0x2;
        }
        buf.writeByte(nullBits);
        final int itemsOffsetSlot = buf.writerIndex();
        buf.writeIntLE(0);
        final int blockMapOffsetSlot = buf.writerIndex();
        buf.writeIntLE(0);
        final int varBlockStart = buf.writerIndex();
        if (this.items != null) {
            buf.setIntLE(itemsOffsetSlot, buf.writerIndex() - varBlockStart);
            if (this.items.length > 4096000) {
                throw ProtocolException.arrayTooLong("Items", this.items.length, 4096000);
            }
            VarInt.write(buf, this.items.length);
            for (final ItemBase item : this.items) {
                item.serialize(buf);
            }
        }
        else {
            buf.setIntLE(itemsOffsetSlot, -1);
        }
        if (this.blockMap != null) {
            buf.setIntLE(blockMapOffsetSlot, buf.writerIndex() - varBlockStart);
            if (this.blockMap.length > 4096000) {
                throw ProtocolException.arrayTooLong("BlockMap", this.blockMap.length, 4096000);
            }
            VarInt.write(buf, this.blockMap.length);
            for (final Map<Integer, String> item2 : this.blockMap) {
                VarInt.write(buf, item2.size());
                for (final Map.Entry<Integer, String> entry : item2.entrySet()) {
                    buf.writeIntLE(entry.getKey());
                    PacketIO.writeVarString(buf, entry.getValue(), 4096000);
                }
            }
        }
        else {
            buf.setIntLE(blockMapOffsetSlot, -1);
        }
    }
    
    public int computeSize() {
        int size = 9;
        if (this.items != null) {
            int itemsSize = 0;
            for (final ItemBase elem : this.items) {
                itemsSize += elem.computeSize();
            }
            size += VarInt.size(this.items.length) + itemsSize;
        }
        if (this.blockMap != null) {
            int blockMapSize = 0;
            for (final Map<Integer, String> elem2 : this.blockMap) {
                blockMapSize += VarInt.size(elem2.size()) + elem2.entrySet().stream().mapToInt(kvpInner -> 4 + PacketIO.stringSize(kvpInner.getValue())).sum();
            }
            size += VarInt.size(this.blockMap.length) + blockMapSize;
        }
        return size;
    }
    
    public static ValidationResult validateStructure(@Nonnull final ByteBuf buffer, final int offset) {
        if (buffer.readableBytes() - offset < 9) {
            return ValidationResult.error("Buffer too small: expected at least 9 bytes");
        }
        final byte nullBits = buffer.getByte(offset);
        if ((nullBits & 0x1) != 0x0) {
            final int itemsOffset = buffer.getIntLE(offset + 1);
            if (itemsOffset < 0) {
                return ValidationResult.error("Invalid offset for Items");
            }
            int pos = offset + 9 + itemsOffset;
            if (pos >= buffer.writerIndex()) {
                return ValidationResult.error("Offset out of bounds for Items");
            }
            final int itemsCount = VarInt.peek(buffer, pos);
            if (itemsCount < 0) {
                return ValidationResult.error("Invalid array count for Items");
            }
            if (itemsCount > 4096000) {
                return ValidationResult.error("Items exceeds max length 4096000");
            }
            pos += VarInt.length(buffer, pos);
            for (int i = 0; i < itemsCount; ++i) {
                final ValidationResult structResult = ItemBase.validateStructure(buffer, pos);
                if (!structResult.isValid()) {
                    return ValidationResult.error("Invalid ItemBase in Items[" + i + "]: " + structResult.error());
                }
                pos += ItemBase.computeBytesConsumed(buffer, pos);
            }
        }
        if ((nullBits & 0x2) != 0x0) {
            final int blockMapOffset = buffer.getIntLE(offset + 5);
            if (blockMapOffset < 0) {
                return ValidationResult.error("Invalid offset for BlockMap");
            }
            int pos = offset + 9 + blockMapOffset;
            if (pos >= buffer.writerIndex()) {
                return ValidationResult.error("Offset out of bounds for BlockMap");
            }
            final int blockMapCount = VarInt.peek(buffer, pos);
            if (blockMapCount < 0) {
                return ValidationResult.error("Invalid array count for BlockMap");
            }
            if (blockMapCount > 4096000) {
                return ValidationResult.error("BlockMap exceeds max length 4096000");
            }
            pos += VarInt.length(buffer, pos);
            for (int i = 0; i < blockMapCount; ++i) {
                final int blockMapDictLen = VarInt.peek(buffer, pos);
                if (blockMapDictLen < 0) {
                    return ValidationResult.error("Invalid dictionary count in BlockMap[" + i);
                }
                pos += VarInt.length(buffer, pos);
                for (int j = 0; j < blockMapDictLen; ++j) {
                    pos += 4;
                    if (pos > buffer.writerIndex()) {
                        return ValidationResult.error("Buffer overflow reading blockMapKey");
                    }
                    final int blockMapValLen = VarInt.peek(buffer, pos);
                    if (blockMapValLen < 0) {
                        return ValidationResult.error("Invalid string length for blockMapVal");
                    }
                    if (blockMapValLen > 4096000) {
                        return ValidationResult.error("blockMapVal exceeds max length 4096000");
                    }
                    pos += VarInt.length(buffer, pos);
                    pos += blockMapValLen;
                    if (pos > buffer.writerIndex()) {
                        return ValidationResult.error("Buffer overflow reading blockMapVal");
                    }
                }
            }
        }
        return ValidationResult.OK;
    }
    
    public ItemLibrary clone() {
        final ItemLibrary copy = new ItemLibrary();
        copy.items = (ItemBase[])((this.items != null) ? ((ItemBase[])Arrays.stream(this.items).map(e -> e.clone()).toArray(ItemBase[]::new)) : null);
        copy.blockMap = (Map<Integer, String>[])((this.blockMap != null) ? ((Map[])Arrays.stream(this.blockMap).map(d -> new HashMap(d)).toArray(Map[]::new)) : null);
        return copy;
    }
    
    @Override
    public boolean equals(final Object obj) {
        if (this == obj) {
            return true;
        }
        if (obj instanceof final ItemLibrary other) {
            return Arrays.equals(this.items, other.items) && Arrays.equals(this.blockMap, other.blockMap);
        }
        return false;
    }
    
    @Override
    public int hashCode() {
        int result = 1;
        result = 31 * result + Arrays.hashCode(this.items);
        result = 31 * result + Arrays.hashCode(this.blockMap);
        return result;
    }
}
