/*
 * 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
 */


class PngChunk {
    
    constructor(_typ) {
        this.typ = null;
        this.data = null;
        this.typ = _typ;
    }
    
    toString() {
        return (this.typ + ": " + (this.data === null ? 0 : this.data.length) + "bytes");
    }
    
    write(str) {
        this._writeInt(str, (this.data === null ? 0 : this.data.length));
        for (let i = 0; i < 4; i++) {
            str.writeByte(this.typ.charCodeAt(i));
        }
        if (this.data !== null && this.data.length > 0) 
            str.write(this.data, 0, this.data.length);
        let crc = this._calcCrc();
        this._writeInt(str, crc);
    }
    
    _writeInt(res, val) {
        res.writeByte(((((val) >>> 24)) & 0xFF));
        res.writeByte(((((val) >>> 16)) & 0xFF));
        res.writeByte(((((val) >>> 8)) & 0xFF));
        res.writeByte(((val) & 0xFF));
    }
    
    _calcCrc() {
        let crc = 0xFFFFFFFF;
        for (let i = 0; i < 4; i++) {
            let b = this.typ.charCodeAt(i);
            crc = (PngChunk.m_CrcTable[(((crc) ^ (b))) & 0xff]) ^ (((crc) >>> 8));
        }
        if (this.data !== null) {
            for (let n = 0; n < this.data.length; n++) {
                crc = (PngChunk.m_CrcTable[(((crc) ^ (this.data[n]))) & 0xff]) ^ (((crc) >>> 8));
            }
        }
        return (crc) ^ 0xFFFFFFFF;
    }
    
    static static_constructor() {
        PngChunk.m_CrcTable = null;
        PngChunk.m_CrcTable = Array(256).fill(0);
        for (let n = 0; n < 256; n++) {
            let c = n;
            for (let k = 0; k < 8; k++) {
                if ((((c) & 1)) !== 0) 
                    c = 0xedb88320 ^ (((c) >>> 1));
                else 
                    c = (c) >>> 1;
            }
            PngChunk.m_CrcTable[n] = c;
        }
    }
}


PngChunk.static_constructor();

module.exports = PngChunk