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

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

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

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


    const language_tag = buffer.readASCIICharacters(Number.MAX_SAFE_INTEGER, true);
    const translated_keyword = buffer.readASCIICharacters(Number.MAX_SAFE_INTEGER, true);

    const remaining_bytes = chunk_byte_end - buffer.position;

    let text;

    if (compression_flag === 0) {
        text = buffer.readASCIICharacters(remaining_bytes);
    } else if (compression_flag === 1) {

        if (compression_method !== 0) {
            throw new Error('only compression_method 0 is supported');
        }

        const decoded = inflate(new Uint8Array(buffer.data, buffer.position, remaining_bytes));

        buffer.fromArrayBuffer(decoded);

        text = buffer.readASCIICharacters(decoded.byteLength);
    } else {
        throw new Error(`Invalid compression flag value '${compression_flag}'`);
    }

    return {
        keyword,
        language_tag,
        translated_keyword,
        text
    }
}