import { BinaryBuffer } from "../../../../../../core/binary/BinaryBuffer.js";
import { inflate } from "../inflate.js";

/**
 * Compressed textual data
 * @see https://www.w3.org/TR/2003/REC-PNG-20031110/#11zTXt
 * @param {Uint8Array} chunk
 */
export function png_chunk_decode_zTXt(chunk) {
    const chunk_size = chunk.byteLength;
    const chunk_buffer = chunk.buffer;
    const chunk_byte_offset = chunk.byteOffset;

    const buffer = BinaryBuffer.fromArrayBuffer(chunk_buffer);
    buffer.position = chunk_byte_offset;

    const keyword = buffer.readASCIICharacters(79, true);

    const compression_method = buffer.readUint8();

    let value;

    if (compression_method === 0) {
        // deflate method

        const local_offset = buffer.position - chunk_byte_offset;
        const encoded_chunk = new Uint8Array(chunk_buffer, buffer.position, chunk_size  - local_offset);

        const decompressed_data = inflate(encoded_chunk);

        buffer.fromArrayBuffer(decompressed_data);

        value = buffer.readASCIICharacters(decompressed_data.byteLength);
    } else {
        throw new Error(`Unsupported compression method '${compression_method}'`);
    }

    return {
        keyword: keyword,
        text: value
    }
}