import { JpegImage } from "./JpegImage.js";

/**
 *
 * @param {ArrayBuffer} jpegData
 * @param [userOpts]
 * @return {{width: number, height: number, exifBuffer: Uint8Array, data: Uint8Array}}
 */
export function jpeg_decode(jpegData, userOpts = {}) {
    const defaultOpts = {
        // "undefined" means "Choose whether to transform colors based on the image’s color model."
        colorTransform: undefined,
        tolerantDecoding: true,
    };

    const opts = { ...defaultOpts, ...userOpts };
    const arr = new Uint8Array(jpegData);
    const decoder = new JpegImage();
    decoder.opts = opts;
    // If this constructor ever supports async decoding this will need to be done differently.
    // Until then, treating as singleton limit is fine.
    decoder.parse(arr);

    const channels =  3;
    const bytesNeeded = decoder.width * decoder.height * channels;

    const image = {
        width: decoder.width,
        height: decoder.height,
        exifBuffer: decoder.exifBuffer,
        data: new Uint8Array(bytesNeeded)
    };

    if (decoder.comments.length > 0) {
        image["comments"] = decoder.comments;
    }

    decoder.copyToImageData(image, false);

    return image;
}