/*
 * SDK Pullenti Unitext, version 4.33, fabruary 2026. Copyright (c) 2013-2026, Pullenti. All rights reserved. 
 * Non-Commercial Freeware and Commercial Software. 
 * This class is generated using the converter Unisharping (www.unisharping.ru) from Pullenti C# project. 
 * The latest version of the code is available on the site www.pullenti.ru
 */

package com.pullenti.unitext.internal.misc;

public class PngChunk {

    public PngChunk(String _typ) {
        typ = _typ;
    }

    public String typ;

    public byte[] data;

    @Override
    public String toString() {
        return (typ + ": " + (data == null ? 0 : data.length) + "bytes");
    }

    public void write(com.pullenti.unisharp.Stream str) throws java.io.IOException {
        this._writeInt(str, (int)((data == null ? 0 : data.length)));
        for (int i = 0; i < 4; i++) {
            str.write((byte)typ.charAt(i));
        }
        if (data != null && data.length > 0) 
            str.write(data, 0, data.length);
        int crc = this._calcCrc();
        this._writeInt(str, crc);
    }

    private void _writeInt(com.pullenti.unisharp.Stream res, int val) throws java.io.IOException {
        res.write((byte)((((((int)val) >>> 24)) & 0xFF)));
        res.write((byte)((((((int)val) >>> 16)) & 0xFF)));
        res.write((byte)((((((int)val) >>> 8)) & 0xFF)));
        res.write((byte)((((int)val) & 0xFF)));
    }

    private int _calcCrc() {
        int crc = (int)0xFFFFFFFF;
        for (int i = 0; i < 4; i++) {
            byte b = (byte)typ.charAt(i);
            crc = (int)(((int)m_CrcTable[((((int)crc) ^ (Byte.toUnsignedInt(b)))) & 0xff]) ^ ((((int)crc) >>> 8)));
        }
        if (data != null) {
            for (int n = 0; n < data.length; n++) {
                crc = (int)(((int)m_CrcTable[((((int)crc) ^ (Byte.toUnsignedInt(data[n])))) & 0xff]) ^ ((((int)crc) >>> 8)));
            }
        }
        return (int)(((int)crc) ^ 0xFFFFFFFF);
    }

    private static int[] m_CrcTable;

    public PngChunk() {
    }
    
    static {
        m_CrcTable = new int[256];
        for (int n = 0; n < 256; n++) {
            int c = (int)n;
            for (int k = 0; k < 8; k++) {
                if (((((int)c) & 1)) != 0) 
                    c = (int)(0xedb88320 ^ ((((int)c) >>> 1)));
                else 
                    c = (int)(((int)c) >>> 1);
            }
            m_CrcTable[n] = c;
        }
    }
}
