extern crate pdf_render;

use crate::{t, CosFile};

use image::{DynamicImage, RgbaImage};
use pathfinder_geometry::transform2d::Transform2F;
use pathfinder_rasterize::Rasterizer;
use pdf::object::Page;
use pdf_render::{render_page, Cache, SceneBackend};

pub struct Renderer<'a> {
    file: &'a CosFile,
    cache: Cache,
    transform: Transform2F,
}

impl<'a> Renderer<'a> {
    pub fn new(file: &'a CosFile, dpi: u32) -> Renderer<'a> {
        Renderer {
            file,
            cache: Cache::new(),
            transform: Transform2F::from_scale(dpi as f32 / 25.4),
        }
    }

    pub fn render(&mut self, page: &Page) -> Result<DynamicImage, String> {
        let resolver = self.file.resolver();
        let mut backend = SceneBackend::new(&mut self.cache);
        t!(render_page(&mut backend, &resolver, &page, self.transform));
        let scene = backend.finish();
        let mut rasterizer = Rasterizer::new();
        Ok(DynamicImage::ImageRgba8(rasterizer.rasterize(scene, None)))
    }
}

pub fn render(file: &CosFile, page_num: u32) -> Result<RgbaImage, String> {
    render_with_dpi(file, page_num, 300)
}
pub fn render_with_dpi(file: &CosFile, page_num: u32, dpi: u32) -> Result<RgbaImage, String> {
    let resolver = file.resolver();
    let page = t!(file.get_page(page_num));

    let mut cache = Cache::new();
    let mut backend = SceneBackend::new(&mut cache);

    t!(render_page(
        &mut backend,
        &resolver,
        &page,
        Transform2F::from_scale(dpi as f32 / 25.4)
    ));
    Ok(Rasterizer::new().rasterize(backend.finish(), None))
}
