mod widget;

pub use self::widget::{ImageType, ImageWidget};
use crate::WidgetBuilder;
use crate::elements::Image;
use gtk4::glib::{self, MainContext, clone};
use gtk4::{Align, Orientation, Overflow, Widget, prelude::*};

impl WidgetBuilder {
    pub(super) fn create_image(&self, image: Image, image_type: ImageType) -> Widget {
        let Some(downloader) = self.image_downloader.clone() else {
            return gtk4::Image::builder()
                .icon_name("image-missing")
                .icon_size(gtk4::IconSize::Large)
                .build()
                .upcast();
        };

        let widget = widget::ImageWidget::new(image_type, self.config.font_size);

        for id in &image.ids {
            tracing::trace!(id, "instert image into id_map");
            self.id_map
                .borrow_mut()
                .insert(id.clone(), widget.clone().upcast());
        }

        MainContext::default().spawn_local(clone!(
            #[weak]
            widget,
            #[strong(rename_to = content_id)]
            self.content_id,
            async move { widget.load(content_id.as_str(), image, downloader).await }
        ));

        widget.upcast()
    }

    pub(super) fn create_image_gallery(&self, images: Vec<Image>) -> Widget {
        let carousel = libadwaita::Carousel::builder()
            .allow_mouse_drag(true)
            .allow_scroll_wheel(false)
            .css_classes(["rounded-edges"])
            .overflow(Overflow::Hidden)
            .build();
        let dots = libadwaita::CarouselIndicatorDots::builder()
            .carousel(&carousel)
            .valign(Align::End)
            .build();

        let gallery = gtk4::Box::builder()
            .orientation(Orientation::Vertical)
            .spacing(5)
            .margin_top(5)
            .margin_bottom(5)
            .build();
        gallery.append(&carousel);
        gallery.append(&dots);

        for image in images {
            let image_widget = self.create_image(image, ImageType::Gallery);
            carousel.append(&image_widget);
        }

        gallery.upcast()
    }
}
