//! Delivery of finished screen captures to their sink.

use super::*;

/// Where a queued screenshot's PNG should go once the render pass encodes it.
#[derive(Debug)]
pub enum ScreenshotSink {
    Clipboard,
    PortalFile(async_channel::Sender<crate::portal_dbus::PortalReply>),
    /// Decode the captured pixels and reply with the top-left pixel's color.
    PickColor(async_channel::Sender<crate::portal_dbus::PortalReply>),
}

impl Windows {
    /// Route an encoded screenshot to its sink: the clipboard staging slot, or
    /// a fresh file whose `file://` URI is returned to the portal.
    pub fn deliver_screenshot(&mut self, result: Result<Vec<u8>, String>, sink: ScreenshotSink) {
        use crate::portal_dbus::PortalReply;
        match sink {
            ScreenshotSink::Clipboard => match result {
                Ok(bytes) => self.screenshot_result = Some(bytes),
                Err(e) => tracing::warn!("screenshot capture failed: {e}"),
            },
            ScreenshotSink::PortalFile(reply) => {
                let msg = match result {
                    Ok(bytes) => match crate::screenshot::paths::write_screenshot_png(&bytes) {
                        Ok(uri) => PortalReply::Uri(uri),
                        Err(e) => {
                            tracing::warn!("portal screenshot write failed: {e}");
                            PortalReply::Failed
                        }
                    },
                    Err(e) => {
                        tracing::warn!("portal screenshot capture failed: {e}");
                        PortalReply::Failed
                    }
                };
                let _ = reply.try_send(msg);
            }
            ScreenshotSink::PickColor(reply) => {
                let msg = result
                    .map_err(|e| tracing::warn!("pick color capture failed: {e}"))
                    .ok()
                    .and_then(|bytes| image::load_from_memory(&bytes).ok())
                    .and_then(|img| {
                        let rgba = img.into_rgba8();
                        rgba.get_pixel_checked(0, 0).copied()
                    })
                    .map(|px| PortalReply::Color(
                        px[0] as f64 / 255.0,
                        px[1] as f64 / 255.0,
                        px[2] as f64 / 255.0,
                    ))
                    .unwrap_or(PortalReply::Failed);
                let _ = reply.try_send(msg);
            }
        }
    }


}
