/// Inhibit the screensave on linux via d-bus
pub(crate) struct ScreensaverInhibitor {
    conn: zbus::blocking::Connection,
    cookie: u32,
}

impl ScreensaverInhibitor {
    pub(crate) fn new() -> Option<Self> {
        let conn = zbus::blocking::Connection::session()
            .map_err(|e| log::warn!("screensaver: session bus failed: {e}"))
            .ok()?;
        let proxy = zbus::blocking::Proxy::new(
            &conn,
            "org.freedesktop.ScreenSaver",
            "/org/freedesktop/ScreenSaver",
            "org.freedesktop.ScreenSaver",
        )
        .map_err(|e| log::warn!("screensaver: proxy creation failed: {e}"))
        .ok()?;
        let app_name = std::env::var("FLATPAK_ID").unwrap_or_else(|_| {
            std::env::current_exe()
                .ok()
                .and_then(|p| p.file_name().map(|n| n.to_string_lossy().into_owned()))
                .unwrap_or_else(|| "myplayer".to_string())
        });
        let cookie: u32 = proxy
            .call("Inhibit", &(app_name.as_str(), "Playing video"))
            .map_err(|e| log::warn!("screensaver: Inhibit call failed: {e}"))
            .ok()?;
        log::debug!("screensaver: inhibited as '{app_name}', cookie={cookie}");
        Some(Self { conn, cookie })
    }
}

impl Drop for ScreensaverInhibitor {
    fn drop(&mut self) {
        if let Ok(proxy) = zbus::blocking::Proxy::new(
            &self.conn,
            "org.freedesktop.ScreenSaver",
            "/org/freedesktop/ScreenSaver",
            "org.freedesktop.ScreenSaver",
        ) {
            let _: zbus::Result<()> = proxy.call("UnInhibit", &(self.cookie,));
        }
    }
}
