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

package com.hypixel.hytale.protocol;

import java.util.Objects;
import java.util.Arrays;
import com.hypixel.hytale.protocol.io.ValidationResult;
import java.util.Iterator;
import java.util.HashMap;
import com.hypixel.hytale.protocol.io.PacketIO;
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 WorldEnvironment
{
    public static final int NULLABLE_BIT_FIELD_SIZE = 1;
    public static final int FIXED_BLOCK_SIZE = 4;
    public static final int VARIABLE_FIELD_COUNT = 3;
    public static final int VARIABLE_BLOCK_START = 16;
    public static final int MAX_SIZE = 1677721600;
    @Nullable
    public String id;
    @Nullable
    public Color waterTint;
    @Nullable
    public Map<Integer, FluidParticle> fluidParticles;
    @Nullable
    public int[] tagIndexes;
    
    public WorldEnvironment() {
    }
    
    public WorldEnvironment(@Nullable final String id, @Nullable final Color waterTint, @Nullable final Map<Integer, FluidParticle> fluidParticles, @Nullable final int[] tagIndexes) {
        this.id = id;
        this.waterTint = waterTint;
        this.fluidParticles = fluidParticles;
        this.tagIndexes = tagIndexes;
    }
    
    public WorldEnvironment(@Nonnull final WorldEnvironment other) {
        this.id = other.id;
        this.waterTint = other.waterTint;
        this.fluidParticles = other.fluidParticles;
        this.tagIndexes = other.tagIndexes;
    }
    
    @Nonnull
    public static WorldEnvironment deserialize(@Nonnull final ByteBuf buf, final int offset) {
        final WorldEnvironment obj = new WorldEnvironment();
        final byte nullBits = buf.getByte(offset);
        if ((nullBits & 0x1) != 0x0) {
            obj.waterTint = Color.deserialize(buf, offset + 1);
        }
        if ((nullBits & 0x2) != 0x0) {
            final int varPos0 = offset + 16 + buf.getIntLE(offset + 4);
            final int idLen = VarInt.peek(buf, varPos0);
            if (idLen < 0) {
                throw ProtocolException.negativeLength("Id", idLen);
            }
            if (idLen > 4096000) {
                throw ProtocolException.stringTooLong("Id", idLen, 4096000);
            }
            obj.id = PacketIO.readVarString(buf, varPos0, PacketIO.UTF8);
        }
        if ((nullBits & 0x4) != 0x0) {
            final int varPos2 = offset + 16 + buf.getIntLE(offset + 8);
            final int fluidParticlesCount = VarInt.peek(buf, varPos2);
            if (fluidParticlesCount < 0) {
                throw ProtocolException.negativeLength("FluidParticles", fluidParticlesCount);
            }
            if (fluidParticlesCount > 4096000) {
                throw ProtocolException.dictionaryTooLarge("FluidParticles", fluidParticlesCount, 4096000);
            }
            final int varIntLen = VarInt.length(buf, varPos2);
            obj.fluidParticles = new HashMap<Integer, FluidParticle>(fluidParticlesCount);
            int dictPos = varPos2 + varIntLen;
            for (int i = 0; i < fluidParticlesCount; ++i) {
                final int key = buf.getIntLE(dictPos);
                dictPos += 4;
                final FluidParticle val = FluidParticle.deserialize(buf, dictPos);
                dictPos += FluidParticle.computeBytesConsumed(buf, dictPos);
                if (obj.fluidParticles.put(key, val) != null) {
                    throw ProtocolException.duplicateKey("fluidParticles", key);
                }
            }
        }
        if ((nullBits & 0x8) != 0x0) {
            final int varPos3 = offset + 16 + buf.getIntLE(offset + 12);
            final int tagIndexesCount = VarInt.peek(buf, varPos3);
            if (tagIndexesCount < 0) {
                throw ProtocolException.negativeLength("TagIndexes", tagIndexesCount);
            }
            if (tagIndexesCount > 4096000) {
                throw ProtocolException.arrayTooLong("TagIndexes", tagIndexesCount, 4096000);
            }
            final int varIntLen = VarInt.length(buf, varPos3);
            if (varPos3 + varIntLen + tagIndexesCount * 4L > buf.readableBytes()) {
                throw ProtocolException.bufferTooSmall("TagIndexes", varPos3 + varIntLen + tagIndexesCount * 4, buf.readableBytes());
            }
            obj.tagIndexes = new int[tagIndexesCount];
            for (int j = 0; j < tagIndexesCount; ++j) {
                obj.tagIndexes[j] = buf.getIntLE(varPos3 + varIntLen + j * 4);
            }
        }
        return obj;
    }
    
    public static int computeBytesConsumed(@Nonnull final ByteBuf buf, final int offset) {
        final byte nullBits = buf.getByte(offset);
        int maxEnd = 16;
        if ((nullBits & 0x2) != 0x0) {
            final int fieldOffset0 = buf.getIntLE(offset + 4);
            int pos0 = offset + 16 + fieldOffset0;
            final int sl = VarInt.peek(buf, pos0);
            pos0 += VarInt.length(buf, pos0) + sl;
            if (pos0 - offset > maxEnd) {
                maxEnd = pos0 - offset;
            }
        }
        if ((nullBits & 0x4) != 0x0) {
            final int fieldOffset2 = buf.getIntLE(offset + 8);
            int pos2 = offset + 16 + fieldOffset2;
            final int dictLen = VarInt.peek(buf, pos2);
            pos2 += VarInt.length(buf, pos2);
            for (int i = 0; i < dictLen; ++i) {
                pos2 += 4;
                pos2 += FluidParticle.computeBytesConsumed(buf, pos2);
            }
            if (pos2 - offset > maxEnd) {
                maxEnd = pos2 - offset;
            }
        }
        if ((nullBits & 0x8) != 0x0) {
            final int fieldOffset3 = buf.getIntLE(offset + 12);
            int pos3 = offset + 16 + fieldOffset3;
            final int arrLen = VarInt.peek(buf, pos3);
            pos3 += VarInt.length(buf, pos3) + arrLen * 4;
            if (pos3 - offset > maxEnd) {
                maxEnd = pos3 - offset;
            }
        }
        return maxEnd;
    }
    
    public void serialize(@Nonnull final ByteBuf buf) {
        final int startPos = buf.writerIndex();
        byte nullBits = 0;
        if (this.waterTint != null) {
            nullBits |= 0x1;
        }
        if (this.id != null) {
            nullBits |= 0x2;
        }
        if (this.fluidParticles != null) {
            nullBits |= 0x4;
        }
        if (this.tagIndexes != null) {
            nullBits |= 0x8;
        }
        buf.writeByte(nullBits);
        if (this.waterTint != null) {
            this.waterTint.serialize(buf);
        }
        else {
            buf.writeZero(3);
        }
        final int idOffsetSlot = buf.writerIndex();
        buf.writeIntLE(0);
        final int fluidParticlesOffsetSlot = buf.writerIndex();
        buf.writeIntLE(0);
        final int tagIndexesOffsetSlot = buf.writerIndex();
        buf.writeIntLE(0);
        final int varBlockStart = buf.writerIndex();
        if (this.id != null) {
            buf.setIntLE(idOffsetSlot, buf.writerIndex() - varBlockStart);
            PacketIO.writeVarString(buf, this.id, 4096000);
        }
        else {
            buf.setIntLE(idOffsetSlot, -1);
        }
        if (this.fluidParticles != null) {
            buf.setIntLE(fluidParticlesOffsetSlot, buf.writerIndex() - varBlockStart);
            if (this.fluidParticles.size() > 4096000) {
                throw ProtocolException.dictionaryTooLarge("FluidParticles", this.fluidParticles.size(), 4096000);
            }
            VarInt.write(buf, this.fluidParticles.size());
            for (final Map.Entry<Integer, FluidParticle> e : this.fluidParticles.entrySet()) {
                buf.writeIntLE(e.getKey());
                e.getValue().serialize(buf);
            }
        }
        else {
            buf.setIntLE(fluidParticlesOffsetSlot, -1);
        }
        if (this.tagIndexes != null) {
            buf.setIntLE(tagIndexesOffsetSlot, buf.writerIndex() - varBlockStart);
            if (this.tagIndexes.length > 4096000) {
                throw ProtocolException.arrayTooLong("TagIndexes", this.tagIndexes.length, 4096000);
            }
            VarInt.write(buf, this.tagIndexes.length);
            for (final int item : this.tagIndexes) {
                buf.writeIntLE(item);
            }
        }
        else {
            buf.setIntLE(tagIndexesOffsetSlot, -1);
        }
    }
    
    public int computeSize() {
        int size = 16;
        if (this.id != null) {
            size += PacketIO.stringSize(this.id);
        }
        if (this.fluidParticles != null) {
            int fluidParticlesSize = 0;
            for (final Map.Entry<Integer, FluidParticle> kvp : this.fluidParticles.entrySet()) {
                fluidParticlesSize += 4 + kvp.getValue().computeSize();
            }
            size += VarInt.size(this.fluidParticles.size()) + fluidParticlesSize;
        }
        if (this.tagIndexes != null) {
            size += VarInt.size(this.tagIndexes.length) + this.tagIndexes.length * 4;
        }
        return size;
    }
    
    public static ValidationResult validateStructure(@Nonnull final ByteBuf buffer, final int offset) {
        if (buffer.readableBytes() - offset < 16) {
            return ValidationResult.error("Buffer too small: expected at least 16 bytes");
        }
        final byte nullBits = buffer.getByte(offset);
        if ((nullBits & 0x2) != 0x0) {
            final int idOffset = buffer.getIntLE(offset + 4);
            if (idOffset < 0) {
                return ValidationResult.error("Invalid offset for Id");
            }
            int pos = offset + 16 + idOffset;
            if (pos >= buffer.writerIndex()) {
                return ValidationResult.error("Offset out of bounds for Id");
            }
            final int idLen = VarInt.peek(buffer, pos);
            if (idLen < 0) {
                return ValidationResult.error("Invalid string length for Id");
            }
            if (idLen > 4096000) {
                return ValidationResult.error("Id exceeds max length 4096000");
            }
            pos += VarInt.length(buffer, pos);
            pos += idLen;
            if (pos > buffer.writerIndex()) {
                return ValidationResult.error("Buffer overflow reading Id");
            }
        }
        if ((nullBits & 0x4) != 0x0) {
            final int fluidParticlesOffset = buffer.getIntLE(offset + 8);
            if (fluidParticlesOffset < 0) {
                return ValidationResult.error("Invalid offset for FluidParticles");
            }
            int pos = offset + 16 + fluidParticlesOffset;
            if (pos >= buffer.writerIndex()) {
                return ValidationResult.error("Offset out of bounds for FluidParticles");
            }
            final int fluidParticlesCount = VarInt.peek(buffer, pos);
            if (fluidParticlesCount < 0) {
                return ValidationResult.error("Invalid dictionary count for FluidParticles");
            }
            if (fluidParticlesCount > 4096000) {
                return ValidationResult.error("FluidParticles exceeds max length 4096000");
            }
            pos += VarInt.length(buffer, pos);
            for (int i = 0; i < fluidParticlesCount; ++i) {
                pos += 4;
                if (pos > buffer.writerIndex()) {
                    return ValidationResult.error("Buffer overflow reading key");
                }
                pos += FluidParticle.computeBytesConsumed(buffer, pos);
            }
        }
        if ((nullBits & 0x8) != 0x0) {
            final int tagIndexesOffset = buffer.getIntLE(offset + 12);
            if (tagIndexesOffset < 0) {
                return ValidationResult.error("Invalid offset for TagIndexes");
            }
            int pos = offset + 16 + tagIndexesOffset;
            if (pos >= buffer.writerIndex()) {
                return ValidationResult.error("Offset out of bounds for TagIndexes");
            }
            final int tagIndexesCount = VarInt.peek(buffer, pos);
            if (tagIndexesCount < 0) {
                return ValidationResult.error("Invalid array count for TagIndexes");
            }
            if (tagIndexesCount > 4096000) {
                return ValidationResult.error("TagIndexes exceeds max length 4096000");
            }
            pos += VarInt.length(buffer, pos);
            pos += tagIndexesCount * 4;
            if (pos > buffer.writerIndex()) {
                return ValidationResult.error("Buffer overflow reading TagIndexes");
            }
        }
        return ValidationResult.OK;
    }
    
    public WorldEnvironment clone() {
        final WorldEnvironment copy = new WorldEnvironment();
        copy.id = this.id;
        copy.waterTint = ((this.waterTint != null) ? this.waterTint.clone() : null);
        if (this.fluidParticles != null) {
            final Map<Integer, FluidParticle> m = new HashMap<Integer, FluidParticle>();
            for (final Map.Entry<Integer, FluidParticle> e : this.fluidParticles.entrySet()) {
                m.put(e.getKey(), e.getValue().clone());
            }
            copy.fluidParticles = m;
        }
        copy.tagIndexes = (int[])((this.tagIndexes != null) ? Arrays.copyOf(this.tagIndexes, this.tagIndexes.length) : null);
        return copy;
    }
    
    @Override
    public boolean equals(final Object obj) {
        if (this == obj) {
            return true;
        }
        if (obj instanceof final WorldEnvironment other) {
            return Objects.equals(this.id, other.id) && Objects.equals(this.waterTint, other.waterTint) && Objects.equals(this.fluidParticles, other.fluidParticles) && Arrays.equals(this.tagIndexes, other.tagIndexes);
        }
        return false;
    }
    
    @Override
    public int hashCode() {
        int result = 1;
        result = 31 * result + Objects.hashCode(this.id);
        result = 31 * result + Objects.hashCode(this.waterTint);
        result = 31 * result + Objects.hashCode(this.fluidParticles);
        result = 31 * result + Arrays.hashCode(this.tagIndexes);
        return result;
    }
}
