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

package com.hypixel.hytale.protocol;

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

public class EntityUpdate
{
    public static final int NULLABLE_BIT_FIELD_SIZE = 1;
    public static final int FIXED_BLOCK_SIZE = 5;
    public static final int VARIABLE_FIELD_COUNT = 2;
    public static final int VARIABLE_BLOCK_START = 13;
    public static final int MAX_SIZE = 1677721600;
    public int networkId;
    @Nullable
    public ComponentUpdateType[] removed;
    @Nullable
    public ComponentUpdate[] updates;
    
    public EntityUpdate() {
    }
    
    public EntityUpdate(final int networkId, @Nullable final ComponentUpdateType[] removed, @Nullable final ComponentUpdate[] updates) {
        this.networkId = networkId;
        this.removed = removed;
        this.updates = updates;
    }
    
    public EntityUpdate(@Nonnull final EntityUpdate other) {
        this.networkId = other.networkId;
        this.removed = other.removed;
        this.updates = other.updates;
    }
    
    @Nonnull
    public static EntityUpdate deserialize(@Nonnull final ByteBuf buf, final int offset) {
        final EntityUpdate obj = new EntityUpdate();
        final byte nullBits = buf.getByte(offset);
        obj.networkId = buf.getIntLE(offset + 1);
        if ((nullBits & 0x1) != 0x0) {
            final int varPos0 = offset + 13 + buf.getIntLE(offset + 5);
            final int removedCount = VarInt.peek(buf, varPos0);
            if (removedCount < 0) {
                throw ProtocolException.negativeLength("Removed", removedCount);
            }
            if (removedCount > 4096000) {
                throw ProtocolException.arrayTooLong("Removed", removedCount, 4096000);
            }
            final int varIntLen = VarInt.length(buf, varPos0);
            if (varPos0 + varIntLen + removedCount * 1L > buf.readableBytes()) {
                throw ProtocolException.bufferTooSmall("Removed", varPos0 + varIntLen + removedCount * 1, buf.readableBytes());
            }
            obj.removed = new ComponentUpdateType[removedCount];
            int elemPos = varPos0 + varIntLen;
            for (int i = 0; i < removedCount; ++i) {
                obj.removed[i] = ComponentUpdateType.fromValue(buf.getByte(elemPos));
                ++elemPos;
            }
        }
        if ((nullBits & 0x2) != 0x0) {
            final int varPos2 = offset + 13 + buf.getIntLE(offset + 9);
            final int updatesCount = VarInt.peek(buf, varPos2);
            if (updatesCount < 0) {
                throw ProtocolException.negativeLength("Updates", updatesCount);
            }
            if (updatesCount > 4096000) {
                throw ProtocolException.arrayTooLong("Updates", updatesCount, 4096000);
            }
            final int varIntLen = VarInt.length(buf, varPos2);
            if (varPos2 + varIntLen + updatesCount * 159L > buf.readableBytes()) {
                throw ProtocolException.bufferTooSmall("Updates", varPos2 + varIntLen + updatesCount * 159, buf.readableBytes());
            }
            obj.updates = new ComponentUpdate[updatesCount];
            int elemPos = varPos2 + varIntLen;
            for (int i = 0; i < updatesCount; ++i) {
                obj.updates[i] = ComponentUpdate.deserialize(buf, elemPos);
                elemPos += ComponentUpdate.computeBytesConsumed(buf, elemPos);
            }
        }
        return obj;
    }
    
    public static int computeBytesConsumed(@Nonnull final ByteBuf buf, final int offset) {
        final byte nullBits = buf.getByte(offset);
        int maxEnd = 13;
        if ((nullBits & 0x1) != 0x0) {
            final int fieldOffset0 = buf.getIntLE(offset + 5);
            int pos0 = offset + 13 + fieldOffset0;
            final int arrLen = VarInt.peek(buf, pos0);
            pos0 += VarInt.length(buf, pos0) + arrLen * 1;
            if (pos0 - offset > maxEnd) {
                maxEnd = pos0 - offset;
            }
        }
        if ((nullBits & 0x2) != 0x0) {
            final int fieldOffset2 = buf.getIntLE(offset + 9);
            int pos2 = offset + 13 + fieldOffset2;
            final int arrLen = VarInt.peek(buf, pos2);
            pos2 += VarInt.length(buf, pos2);
            for (int i = 0; i < arrLen; ++i) {
                pos2 += ComponentUpdate.computeBytesConsumed(buf, pos2);
            }
            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.removed != null) {
            nullBits |= 0x1;
        }
        if (this.updates != null) {
            nullBits |= 0x2;
        }
        buf.writeByte(nullBits);
        buf.writeIntLE(this.networkId);
        final int removedOffsetSlot = buf.writerIndex();
        buf.writeIntLE(0);
        final int updatesOffsetSlot = buf.writerIndex();
        buf.writeIntLE(0);
        final int varBlockStart = buf.writerIndex();
        if (this.removed != null) {
            buf.setIntLE(removedOffsetSlot, buf.writerIndex() - varBlockStart);
            if (this.removed.length > 4096000) {
                throw ProtocolException.arrayTooLong("Removed", this.removed.length, 4096000);
            }
            VarInt.write(buf, this.removed.length);
            for (final ComponentUpdateType item : this.removed) {
                buf.writeByte(item.getValue());
            }
        }
        else {
            buf.setIntLE(removedOffsetSlot, -1);
        }
        if (this.updates != null) {
            buf.setIntLE(updatesOffsetSlot, buf.writerIndex() - varBlockStart);
            if (this.updates.length > 4096000) {
                throw ProtocolException.arrayTooLong("Updates", this.updates.length, 4096000);
            }
            VarInt.write(buf, this.updates.length);
            for (final ComponentUpdate item2 : this.updates) {
                item2.serialize(buf);
            }
        }
        else {
            buf.setIntLE(updatesOffsetSlot, -1);
        }
    }
    
    public int computeSize() {
        int size = 13;
        if (this.removed != null) {
            size += VarInt.size(this.removed.length) + this.removed.length * 1;
        }
        if (this.updates != null) {
            int updatesSize = 0;
            for (final ComponentUpdate elem : this.updates) {
                updatesSize += elem.computeSize();
            }
            size += VarInt.size(this.updates.length) + updatesSize;
        }
        return size;
    }
    
    public static ValidationResult validateStructure(@Nonnull final ByteBuf buffer, final int offset) {
        if (buffer.readableBytes() - offset < 13) {
            return ValidationResult.error("Buffer too small: expected at least 13 bytes");
        }
        final byte nullBits = buffer.getByte(offset);
        if ((nullBits & 0x1) != 0x0) {
            final int removedOffset = buffer.getIntLE(offset + 5);
            if (removedOffset < 0) {
                return ValidationResult.error("Invalid offset for Removed");
            }
            int pos = offset + 13 + removedOffset;
            if (pos >= buffer.writerIndex()) {
                return ValidationResult.error("Offset out of bounds for Removed");
            }
            final int removedCount = VarInt.peek(buffer, pos);
            if (removedCount < 0) {
                return ValidationResult.error("Invalid array count for Removed");
            }
            if (removedCount > 4096000) {
                return ValidationResult.error("Removed exceeds max length 4096000");
            }
            pos += VarInt.length(buffer, pos);
            pos += removedCount * 1;
            if (pos > buffer.writerIndex()) {
                return ValidationResult.error("Buffer overflow reading Removed");
            }
        }
        if ((nullBits & 0x2) != 0x0) {
            final int updatesOffset = buffer.getIntLE(offset + 9);
            if (updatesOffset < 0) {
                return ValidationResult.error("Invalid offset for Updates");
            }
            int pos = offset + 13 + updatesOffset;
            if (pos >= buffer.writerIndex()) {
                return ValidationResult.error("Offset out of bounds for Updates");
            }
            final int updatesCount = VarInt.peek(buffer, pos);
            if (updatesCount < 0) {
                return ValidationResult.error("Invalid array count for Updates");
            }
            if (updatesCount > 4096000) {
                return ValidationResult.error("Updates exceeds max length 4096000");
            }
            pos += VarInt.length(buffer, pos);
            for (int i = 0; i < updatesCount; ++i) {
                final ValidationResult structResult = ComponentUpdate.validateStructure(buffer, pos);
                if (!structResult.isValid()) {
                    return ValidationResult.error("Invalid ComponentUpdate in Updates[" + i + "]: " + structResult.error());
                }
                pos += ComponentUpdate.computeBytesConsumed(buffer, pos);
            }
        }
        return ValidationResult.OK;
    }
    
    public EntityUpdate clone() {
        final EntityUpdate copy = new EntityUpdate();
        copy.networkId = this.networkId;
        copy.removed = (ComponentUpdateType[])((this.removed != null) ? ((ComponentUpdateType[])Arrays.copyOf(this.removed, this.removed.length)) : null);
        copy.updates = (ComponentUpdate[])((this.updates != null) ? ((ComponentUpdate[])Arrays.stream(this.updates).map(e -> e.clone()).toArray(ComponentUpdate[]::new)) : null);
        return copy;
    }
    
    @Override
    public boolean equals(final Object obj) {
        if (this == obj) {
            return true;
        }
        if (obj instanceof final EntityUpdate other) {
            return this.networkId == other.networkId && Arrays.equals(this.removed, other.removed) && Arrays.equals(this.updates, other.updates);
        }
        return false;
    }
    
    @Override
    public int hashCode() {
        int result = 1;
        result = 31 * result + Integer.hashCode(this.networkId);
        result = 31 * result + Arrays.hashCode(this.removed);
        result = 31 * result + Arrays.hashCode(this.updates);
        return result;
    }
}
