use std::{mem::transmute, slice};

use zune_jpeg::{zune_core::{colorspace::ColorSpace, options::DecoderOptions}, JpegDecoder};

#[no_mangle]
pub extern "C" fn add(a: u64, b: u64) -> u64 {
    a + b
}

#[no_mangle]
/// decode jpeg image of given length
///
/// image format is 0RGB
pub extern "C" fn decode(image: &mut u32, packet: &u8, length: u32) -> u64 {
    let packet = unsafe {slice::from_raw_parts(packet, length as usize)};
    let image: &mut [u8; 4*320*240] = unsafe{transmute(image)};

    let options = DecoderOptions::new_fast().jpeg_set_out_colorspace(ColorSpace::RGB);
    let Ok(mut frame) = JpegDecoder::new_with_options(packet, options).decode() else {
        return 1; // decoder failure
    };

    // convert from RGB to 0RGB (and swap endianness)
    for (buffer, image) in frame.chunks_exact_mut(3).zip(image.chunks_exact_mut(4)) {
        image[0] = buffer[2];
        image[1] = buffer[1];
        image[2] = buffer[0];
        image[3] = 0;
    }

    0 // success
}
