//! QuickDraw PICT RGB8 `PixMap`s.

use crate::{bin::check_data, err::*, image::{*, pict::{pm, rle}}};

/// Reads a RGB8 `PixMap`.
pub fn read(mut im: Image8,
            b: &[u8],
            hdr: pm::head::Header) -> ResultS<Image8>
{
	let mut p = 0;

	if hdr.pitch < 8 ||
	   hdr.pack_t == pm::head::PackType::None ||
	   hdr.pack_t == pm::head::PackType::NoPad
	{
		// uncompressed RGB8 or XRGB8
		for _ in 0..im.h() {
			for _ in 0..im.w() {
				if hdr.pack_t != pm::head::PackType::NoPad {
					p += 1;
				}

				read_data! {
					endian: BIG, buf: b, size: 3, start: p, data {
						let r = u8[0];
						let g = u8[1];
						let b = u8[2];
					}
				}

				im.cr.push(Color8::new(r, g, b));

				p += 3;
			}
		}

		Ok(im)
	} else if hdr.rle {
		// RLE compressed RGB8
		let pitch = hdr.pitch - im.w(); // remove padding byte from pitch
		for _ in 0..im.h() {
			let (d, pp) = rle::read::<u8>(&b[p..], pitch)?;

			check_data(&d, im.w() * 3)?;

			p += pp;

			for x in 0..im.w() {
				let r = d[x];
				let g = d[x * 2];
				let b = d[x * 3];
				im.cr.push(Color8::new(r, g, b));
			}
		}

		Ok(im)
	} else {
		bail!("invalid configuration")
	}
}

// EOF
