
use image::{RgbaImage, ExtendedColorType, ImageEncoder, load_from_memory};
use image::codecs::png::PngEncoder;
use tiny_skia::{Pixmap, Transform, PixmapPaint, BlendMode, FilterQuality};

pub fn save_to_memory_png(p: &RgbaImage) -> Result<Vec<u8>, String> {
	let (width, height) = p.dimensions();
	let mut blob = Vec::<u8>::new();
	let png_encoder = PngEncoder::new(&mut blob);
	match png_encoder.write_image(p, width, height, ExtendedColorType::Rgba8) {
		Ok(()) => Ok(blob),
		Err(_) => Err("Failed to encode text png".to_string()),
	}
}

pub fn ensure_32_bit_png(p: &[u8]) -> Result<Vec<u8>, String> {
	let img = match load_from_memory(p) {
		Ok(i) => i,
		Err(e) => return Err(format!("Failed to load png: {e}")),
	};
	save_to_memory_png(&img.into_rgba8())
}

pub fn scale_skia_pixmap(p: Pixmap, width: u32, height: u32) -> Option<Pixmap> {
	let mut new_pixmap = Pixmap::new(width, height)?;
    let width_scale = width as f32 / p.width() as f32;
    let height_scale = height as f32 / p.width() as f32;
    let matrix = Transform::from_scale(width_scale, height_scale);
    let pixmap_paint = PixmapPaint {
    	opacity: 1.0,
    	blend_mode: BlendMode::Source,
    	quality: FilterQuality::Bilinear,
    };
    new_pixmap.draw_pixmap(0, 0, p.as_ref(), &pixmap_paint, matrix, None);
    Some(new_pixmap)
}
