use gtk::prelude::*;
use patchpal::ui::config::Config;

pub(crate) trait GtkFrontendConfig {
    fn store_window_state(&self, window: &gtk::Window, name: &str);
    fn restore_window_state(&self, window: &gtk::Window, name: &str);
    fn init_local_gtk_frontend(&self);
}

impl GtkFrontendConfig for Config {
    fn store_window_state(&self, window: &gtk::Window, name: &str) {
        let size = window.default_size();
        let maximized = window.is_maximized();
        let fullscreen = window.is_fullscreen();
        self.set(format!("{name}-width"), size.0.to_string());
        self.set(format!("{name}-height"), size.1.to_string());
        self.set(format!("{name}-maximized"), maximized.to_string());
        self.set(format!("{name}-fullscreen"), fullscreen.to_string());
    }

    fn restore_window_state(&self, window: &gtk::Window, name: &str)
    {
        window.set_default_size(
            self.get(&format!("{name}-width")).unwrap_or(1024),
            self.get(&format!("{name}-height")).unwrap_or(768),
        );
        window.set_maximized(
            self.get(&format!("{name}-maximized")).unwrap_or(false)
        );
        window.set_fullscreened(
            self.get(&format!("{name}-fullscreen")).unwrap_or(false)
        );
    }

    /// Detect dark theme and store the setting in the local data.
    fn init_local_gtk_frontend(&self) {
        // There's no good way to deal with theming in Gtk. The Gtk developers say we should
        // use CSS. However, CSS support for media queries probing for dark theme was
        // introduced only in Gtk 4.20, which was too recent at the time this comment was
        // written. Worse, even that is not enough. There's no usable concept that would allow
        // us to style substrings in labels (or in other widgets). The label is formatted
        // using Pango and Pango doesn't support CSS. That means we need to detect whether
        // there's dark theme in use. That seems to be possible in 4.20. Until then, we're
        // left with deprecated StyleContext. It got deprecated without having a replacement
        // designed. The Gtk developers basically say "just use the deprecated thing until we
        // come up with something for Gtk 5"[1].
        // Note the "theme_bg_color" thing works only for themes that define that name. What
        // a mess.
        // [1] https://discourse.gnome.org/t/replacement-for-gtk-style-context-get-color/23026/2
        #[allow(deprecated)]
        let color = gtk::Label::new(None).style_context().lookup_color("theme_bg_color");
        let dark_theme = match color {
            Some(color) => color.red() + color.green() + color.blue() < 1.5,
            None => false
        };
        self.set_local("dark_theme", dark_theme.to_string());
    }
}
