// SPDX-License-Identifier: GPL-3.0-or-later

//! An adaptive container that allows to specify a max width for itself.

use std::rc::Rc;

use glib::Cast;
use grx_macros::gtk_component;
use gtk::glib;

use crate::{new_gc, props, ComponentExt};
use libadwaita as adw;

use super::gtk_props::apply;

#[props]
#[derive(Default, Debug)]
pub struct Props {
    /// The maximum width of the clamp.
    pub max_width: u32,
}

pub fn clamp(mut props: Props) -> Rc<Clamp> {
    let clamp = adw::Clamp::builder().build();

    let mw = props.max_width;
    let comp = new_gc!(Clamp { clamp, props });
    if mw > 0 {
        comp.set_max_witdth(mw);
    }
    for c in comp.children().iter() {
        comp.set_child(c.clone());
    }
    apply(comp.clone());
    comp
}

#[gtk_component(libadwaita::Clamp)]
#[derive(Debug)]
pub struct Clamp {}

impl Clamp {
    /// Set the child of this clamp.
    pub fn set_child<C>(self: &Rc<Self>, child: Rc<C>)
    where
        C: ComponentExt + ?Sized,
    {
        let inner = child.inner();
        let w: &gtk::Widget = inner.downcast_ref().unwrap();
        self.widget.set_child(Some(w));
    }

    pub fn set_max_witdth(self: &Rc<Self>, max_width: u32) {
        self.widget.set_maximum_size(max_width as i32);
    }
}
