use crate::prelude::*;

#[macro_export]
macro_rules! gspawn {
    ($future:expr) => {
        let ctx = glib::MainContext::default();
        ctx.spawn_local($future);
    };
}

#[macro_export]
macro_rules! tspawn {
    ($future:expr) => {
        $crate::TOKIO_RUNTIME.spawn($future)
    };
}

pub fn is_flatpak() -> bool {
    let file = gio::File::for_path("/.flatpak-info");
    file.query_exists(gio::Cancellable::NONE)
}

pub fn chrono_to_glib_datetime(chrono: chrono::DateTime<chrono::Utc>) -> Option<glib::DateTime> {
    glib::DateTime::from_unix_utc(chrono.timestamp())
        .ok()
        .and_then(|d| d.to_local().ok())
}

pub fn blurhash_decode_pixbuf(
    blurhash: &str,
    width: u32,
    height: u32,
    punch: f32,
) -> Result<gdk_pixbuf::Pixbuf, blurhash::Error> {
    use std::convert::TryInto;
    let bytes = blurhash::decode(blurhash, width, height, punch)?;
    let width = width.try_into().expect("width fits in i32");
    let height = height.try_into().expect("height fits in i32");
    let buffer = gdk_pixbuf::Pixbuf::from_bytes(
        &gdk_pixbuf::glib::Bytes::from_owned(bytes),
        gdk_pixbuf::Colorspace::Rgb,
        true,
        8,
        width,
        height,
        4 * width,
    );
    Ok(buffer)
}
