1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
//! Collection of methods for images.

use std::str::FromStr;

use gtk::{gdk, gio, prelude::*};
use image::{ColorType, DynamicImage, ImageDecoder, ImageResult};
use matrix_sdk::{
    attachment::{BaseImageInfo, BaseThumbnailInfo, Thumbnail},
    media::{MediaFormat, MediaRequest, MediaThumbnailSettings, MediaThumbnailSize},
    Client,
};
use ruma::{
    api::client::media::get_content_thumbnail::v3::Method,
    events::{
        room::{
            avatar::ImageInfo as AvatarImageInfo, ImageInfo, MediaSource as CommonMediaSource,
            ThumbnailInfo,
        },
        sticker::StickerMediaSource,
    },
    OwnedMxcUri,
};
use tracing::warn;

use crate::{
    components::AnimatedImagePaintable,
    spawn_tokio,
    utils::{matrix::MediaFileError, save_data_to_tmp_file},
    DISABLE_GLYCIN_SANDBOX,
};

/// The default width of a generated thumbnail.
const THUMBNAIL_DEFAULT_WIDTH: u32 = 800;
/// The default height of a generated thumbnail.
const THUMBNAIL_DEFAULT_HEIGHT: u32 = 600;
/// The default dimensions of a generated thumbnail.
const THUMBNAIL_DEFAULT_DIMENSIONS: ImageDimensions = ImageDimensions {
    width: THUMBNAIL_DEFAULT_WIDTH,
    height: THUMBNAIL_DEFAULT_HEIGHT,
};
/// The content type of SVG.
const SVG_CONTENT_TYPE: &str = "image/svg+xml";
/// The content type of WebP.
const WEBP_CONTENT_TYPE: &str = "image/webp";
/// The default WebP quality used for a generated thumbnail.
const WEBP_DEFAULT_QUALITY: f32 = 60.0;
/// The maximum file size threshold in bytes for generating a thumbnail.
///
/// If the file size of the original image is larger than this, we assume it is
/// worth it to generate a thumbnail, even if its dimensions are smaller than
/// wanted. This is particularly helpful for some image formats that can take up
/// a lot of space.
///
/// This is 1MB.
const THUMBNAIL_MAX_FILESIZE_THRESHOLD: u32 = 1024 * 1024;
/// The dimension threshold in pixels before we start to generate a thumbnail.
///
/// If the original image is larger than thumbnail_dimensions + threshold, we
/// assume it's worth it to generate a thumbnail.
const THUMBNAIL_DIMENSIONS_THRESHOLD: u32 = 200;

/// Get an image reader for the given file.
async fn image_reader(file: gio::File) -> Result<glycin::Image<'static>, glycin::ErrorCtx> {
    let mut loader = glycin::Loader::new(file);

    if DISABLE_GLYCIN_SANDBOX {
        loader.sandbox_selector(glycin::SandboxSelector::NotSandboxed);
    }

    spawn_tokio!(async move { loader.load().await })
        .await
        .unwrap()
}

/// Load the given file as an image into a `GdkPaintable`.
///
/// Set `request_dimensions` if the image will be shown at specific dimensions.
/// To show the image at its natural size, set it to `None`.
pub async fn load_image(
    file: gio::File,
    request_dimensions: Option<ImageDimensions>,
) -> Result<gdk::Paintable, glycin::ErrorCtx> {
    let image = image_reader(file).await?;

    let frame_request = request_dimensions.map(|request| {
        let image_info = image.info();

        let original_dimensions = ImageDimensions {
            width: image_info.width,
            height: image_info.height,
        };

        original_dimensions.to_image_loader_request(request)
    });

    let (image, first_frame) = spawn_tokio!(async move {
        let first_frame = if let Some(frame_request) = frame_request {
            image.specific_frame(frame_request).await?
        } else {
            image.next_frame().await?
        };
        Ok((image, first_frame))
    })
    .await
    .unwrap()?;

    let paintable = if first_frame.delay().is_some() {
        AnimatedImagePaintable::new(image, first_frame).upcast()
    } else {
        first_frame.texture().upcast()
    };

    Ok(paintable)
}

/// An API to load image information.
pub enum ImageInfoLoader {
    /// An image file.
    File(gio::File),
    /// A texture in memory.
    Texture(gdk::Texture),
}

impl ImageInfoLoader {
    /// Load the first frame for this source.
    ///
    /// We need to load the first frame of an image so that EXIF rotation is
    /// applied and we get the proper dimensions.
    async fn into_first_frame(self) -> Option<Frame> {
        match self {
            Self::File(file) => {
                let image_reader = image_reader(file).await.ok()?;
                let handle = spawn_tokio!(async move { image_reader.next_frame().await });
                Some(Frame::Glycin(handle.await.unwrap().ok()?))
            }
            Self::Texture(texture) => Some(Frame::Texture(gdk::TextureDownloader::new(&texture))),
        }
    }

    /// Load the information for this image.
    pub async fn load_info(self) -> BaseImageInfo {
        self.into_first_frame()
            .await
            .and_then(|f| f.dimensions())
            .map(Into::into)
            .unwrap_or_else(default_base_image_info)
    }

    /// Load the information for this image and try to generate a thumbnail
    /// given the filesize of the original image.
    pub async fn load_info_and_thumbnail(
        self,
        filesize: Option<u32>,
    ) -> (BaseImageInfo, Option<Thumbnail>) {
        let Some(frame) = self.into_first_frame().await else {
            return (default_base_image_info(), None);
        };

        let dimensions = frame.dimensions();
        let info = dimensions
            .map(Into::into)
            .unwrap_or_else(default_base_image_info);

        if !filesize_is_too_big(filesize)
            && !dimensions
                .is_some_and(|d| d.should_resize_for_thumbnail(THUMBNAIL_DEFAULT_DIMENSIONS))
        {
            // It is not worth it to generate a thumbnail.
            return (info, None);
        }

        let thumbnail = frame.generate_thumbnail();

        (info, thumbnail)
    }
}

impl From<gio::File> for ImageInfoLoader {
    fn from(value: gio::File) -> Self {
        Self::File(value)
    }
}

impl From<gdk::Texture> for ImageInfoLoader {
    fn from(value: gdk::Texture) -> Self {
        Self::Texture(value)
    }
}

/// A frame of an image.
enum Frame {
    /// A frame loaded via glycin.
    Glycin(glycin::Frame),
    /// A downloader for a texture in memory,
    Texture(gdk::TextureDownloader),
}

impl Frame {
    /// The dimensions of the frame.
    fn dimensions(&self) -> Option<ImageDimensions> {
        let (width, height) = match self {
            Self::Glycin(frame) => (frame.width(), frame.height()),
            Self::Texture(downloader) => {
                let texture = downloader.texture();
                (
                    texture.width().try_into().ok()?,
                    texture.height().try_into().ok()?,
                )
            }
        };

        Some(ImageDimensions { width, height })
    }

    /// Whether the memory format of the frame is supported by the image crate.
    fn is_memory_format_supported(&self) -> bool {
        match self {
            Self::Glycin(frame) => {
                matches!(
                    frame.memory_format(),
                    glycin::MemoryFormat::G8
                        | glycin::MemoryFormat::G8a8
                        | glycin::MemoryFormat::R8g8b8
                        | glycin::MemoryFormat::R8g8b8a8
                        | glycin::MemoryFormat::G16
                        | glycin::MemoryFormat::G16a16
                        | glycin::MemoryFormat::R16g16b16
                        | glycin::MemoryFormat::R16g16b16a16
                        | glycin::MemoryFormat::R32g32b32Float
                        | glycin::MemoryFormat::R32g32b32a32Float
                )
            }
            Self::Texture(downloader) => {
                matches!(
                    downloader.format(),
                    gdk::MemoryFormat::G8
                        | gdk::MemoryFormat::G8a8
                        | gdk::MemoryFormat::R8g8b8
                        | gdk::MemoryFormat::R8g8b8a8
                        | gdk::MemoryFormat::G16
                        | gdk::MemoryFormat::G16a16
                        | gdk::MemoryFormat::R16g16b16
                        | gdk::MemoryFormat::R16g16b16a16
                        | gdk::MemoryFormat::R32g32b32Float
                        | gdk::MemoryFormat::R32g32b32a32Float
                )
            }
        }
    }

    /// Generate a thumbnail of this frame.
    fn generate_thumbnail(self) -> Option<Thumbnail> {
        if !self.is_memory_format_supported() {
            return None;
        }

        let image = DynamicImage::from_decoder(self).ok()?;
        let thumbnail = image.thumbnail(THUMBNAIL_DEFAULT_WIDTH, THUMBNAIL_DEFAULT_HEIGHT);

        prepare_thumbnail_for_sending(thumbnail)
    }
}

impl ImageDecoder for Frame {
    fn dimensions(&self) -> (u32, u32) {
        let (width, height) = self.dimensions().map(|d| (d.width, d.height)).unzip();
        (width.unwrap_or(0), height.unwrap_or(0))
    }

    fn color_type(&self) -> ColorType {
        match self {
            Self::Glycin(frame) => match frame.memory_format() {
                glycin::MemoryFormat::G8 => ColorType::L8,
                glycin::MemoryFormat::G8a8 => ColorType::La8,
                glycin::MemoryFormat::R8g8b8 => ColorType::Rgb8,
                glycin::MemoryFormat::R8g8b8a8 => ColorType::Rgba8,
                glycin::MemoryFormat::G16 => ColorType::L16,
                glycin::MemoryFormat::G16a16 => ColorType::La16,
                glycin::MemoryFormat::R16g16b16 => ColorType::Rgb16,
                glycin::MemoryFormat::R16g16b16a16 => ColorType::Rgba16,
                glycin::MemoryFormat::R32g32b32Float => ColorType::Rgb32F,
                glycin::MemoryFormat::R32g32b32a32Float => ColorType::Rgba32F,
                _ => unimplemented!(),
            },
            Self::Texture(downloader) => match downloader.format() {
                gdk::MemoryFormat::G8 => ColorType::L8,
                gdk::MemoryFormat::G8a8 => ColorType::La8,
                gdk::MemoryFormat::R8g8b8 => ColorType::Rgb8,
                gdk::MemoryFormat::R8g8b8a8 => ColorType::Rgba8,
                gdk::MemoryFormat::G16 => ColorType::L16,
                gdk::MemoryFormat::G16a16 => ColorType::La16,
                gdk::MemoryFormat::R16g16b16 => ColorType::Rgb16,
                gdk::MemoryFormat::R16g16b16a16 => ColorType::Rgba16,
                gdk::MemoryFormat::R32g32b32Float => ColorType::Rgb32F,
                gdk::MemoryFormat::R32g32b32a32Float => ColorType::Rgba32F,
                _ => unimplemented!(),
            },
        }
    }

    fn read_image(self, buf: &mut [u8]) -> ImageResult<()>
    where
        Self: Sized,
    {
        let bytes = match &self {
            Self::Glycin(frame) => frame.buf_bytes(),
            Self::Texture(texture) => texture.download_bytes().0,
        };
        buf.copy_from_slice(&bytes);

        Ok(())
    }

    fn read_image_boxed(self: Box<Self>, _buf: &mut [u8]) -> ImageResult<()> {
        unimplemented!()
    }
}

/// Dimensions of an image.
#[derive(Debug, Clone, Copy)]
pub struct ImageDimensions {
    /// The width of the image.
    pub width: u32,
    /// The height of the image.
    pub height: u32,
}

impl ImageDimensions {
    /// Construct an `ImageDimensions` from the given optional values.
    ///
    /// Returns `None` if either of the values are `None`.
    fn from_options(width: Option<u32>, height: Option<u32>) -> Option<Self> {
        Some(Self {
            width: width?,
            height: height?,
        })
    }

    /// Whether these dimensions are bigger than the given dimensions.
    ///
    /// Returns `true` if either `width` or `height` is bigger than or equal to
    /// the given dimensions.
    pub fn is_bigger_than(&self, other: ImageDimensions) -> bool {
        self.width >= other.width || self.height >= other.height
    }

    /// Whether these dimensions should be resized to generate a thumbnail.
    pub fn should_resize_for_thumbnail(&self, thumbnail_dimensions: ImageDimensions) -> bool {
        self.is_bigger_than(thumbnail_dimensions.increase_by(THUMBNAIL_DIMENSIONS_THRESHOLD))
    }

    /// Increase both these dimensions by the given value.
    pub const fn increase_by(mut self, value: u32) -> Self {
        self.width = self.width.saturating_add(value);
        self.height = self.height.saturating_add(value);
        self
    }

    /// Compute the new dimensions for resizing to the requested dimensions
    /// while preserving the aspect ratio of these dimensions and respecting
    /// the given strategy.
    pub fn resize(self, requested_dimensions: ImageDimensions, strategy: ResizeStrategy) -> Self {
        let w_ratio = self.width as f64 / requested_dimensions.width as f64;
        let h_ratio = self.height as f64 / requested_dimensions.height as f64;

        let resize_from_width = match strategy {
            // The largest ratio wins so the frame fits into the requested dimensions.
            ResizeStrategy::Contain => w_ratio > h_ratio,
            // The smallest ratio wins so the frame fills the requested dimensions.
            ResizeStrategy::Cover => w_ratio < h_ratio,
        };

        let (width, height) = if resize_from_width {
            let new_height = self.height as f64 / w_ratio;
            (requested_dimensions.width, new_height as u32)
        } else {
            let new_width = self.width as f64 / h_ratio;
            (new_width as u32, requested_dimensions.height)
        };

        Self { width, height }
    }

    /// Compute the dimensions for a thumbnail while preserving the aspect ratio
    /// of these dimensions.
    ///
    /// Returns `None` if these dimensions are smaller than the wanted
    /// dimensions.
    pub fn resize_for_thumbnail(self) -> Option<Self> {
        let thumbnail_dimensions = THUMBNAIL_DEFAULT_DIMENSIONS;

        if !self.should_resize_for_thumbnail(thumbnail_dimensions) {
            return None;
        }

        Some(self.resize(thumbnail_dimensions, ResizeStrategy::Contain))
    }

    /// Convert these dimensions to a request for the image loader with the
    /// requested dimensions.
    pub fn to_image_loader_request(
        self,
        requested_dimensions: ImageDimensions,
    ) -> glycin::FrameRequest {
        let resized_dimensions = self.resize(requested_dimensions, ResizeStrategy::Cover);
        glycin::FrameRequest::new().scale(resized_dimensions.width, resized_dimensions.height)
    }
}

impl From<ImageDimensions> for BaseImageInfo {
    fn from(value: ImageDimensions) -> Self {
        let ImageDimensions { width, height } = value;
        BaseImageInfo {
            height: Some(height.into()),
            width: Some(width.into()),
            size: None,
            blurhash: None,
        }
    }
}

/// The default value for `BaseImageInfo`.
fn default_base_image_info() -> BaseImageInfo {
    BaseImageInfo {
        height: None,
        width: None,
        size: None,
        blurhash: None,
    }
}

/// The strategy to use when computing the new dimensions for resizing an image
/// while maintaining its aspect ratio.
#[derive(Debug, Clone, Copy)]
pub enum ResizeStrategy {
    /// The image is scaled to fit completely within the new dimensions.
    ///
    /// This is useful if we do not want the image to be cropped to fit inside
    /// maximum dimensions.
    Contain,
    /// The image is sized to maintain its aspect ratio while filling the new
    /// dimensions.
    ///
    /// This is useful if we want the image to be cropped to fit inside the new
    /// dimensions.
    Cover,
}

/// Prepare the given thumbnail to send it.
pub(super) fn prepare_thumbnail_for_sending(thumbnail: image::DynamicImage) -> Option<Thumbnail> {
    // Convert to RGB8/RGBA8 since those are the only formats supported by WebP.
    let thumbnail: DynamicImage = match &thumbnail {
        DynamicImage::ImageLuma8(_)
        | DynamicImage::ImageRgb8(_)
        | DynamicImage::ImageLuma16(_)
        | DynamicImage::ImageRgb16(_)
        | DynamicImage::ImageRgb32F(_) => thumbnail.into_rgb8().into(),
        DynamicImage::ImageLumaA8(_)
        | DynamicImage::ImageRgba8(_)
        | DynamicImage::ImageLumaA16(_)
        | DynamicImage::ImageRgba16(_)
        | DynamicImage::ImageRgba32F(_) => thumbnail.into_rgba8().into(),
        _ => return None,
    };

    // Encode to WebP.
    let encoder = webp::Encoder::from_image(&thumbnail).ok()?;
    let thumbnail_bytes = encoder.encode(WEBP_DEFAULT_QUALITY).to_vec();

    let thumbnail_content_type =
        mime::Mime::from_str(WEBP_CONTENT_TYPE).expect("content type should be valid");

    let thumbnail_info = BaseThumbnailInfo {
        width: Some(thumbnail.width().into()),
        height: Some(thumbnail.height().into()),
        size: thumbnail_bytes.len().try_into().ok(),
    };

    Some(Thumbnail {
        data: thumbnail_bytes,
        content_type: thumbnail_content_type,
        info: Some(thumbnail_info),
    })
}

/// An API to download a thumbnail for a media.
#[derive(Debug, Clone, Copy)]
pub struct ThumbnailDownloader<'a> {
    /// The main source of the image.
    ///
    /// This should be the source with the best quality.
    pub main: ImageSource<'a>,
    /// An alternative source for the image.
    ///
    /// This should be a source with a lower quality.
    pub alt: Option<ImageSource<'a>>,
}

impl<'a> ThumbnailDownloader<'a> {
    /// Download the thumbnail of the media.
    ///
    /// This might not return a thumbnail at the requested size, depending on
    /// the sources and the homeserver.
    ///
    /// Returns `Ok(None)` if no thumbnail could be retrieved. Returns an error
    /// if something occurred while fetching the content.
    pub async fn download_to_file(
        self,
        client: &Client,
        settings: ThumbnailSettings,
    ) -> Result<gio::File, MediaFileError> {
        // First, select which source we are going to download from.
        let source = if let Some(alt) = self.alt {
            if !self.main.can_be_thumbnailed()
                && (filesize_is_too_big(self.main.filesize())
                    || alt
                        .dimensions()
                        .is_some_and(|d| d.is_bigger_than(settings.dimensions)))
            {
                // Use the alternative source to save bandwidth.
                alt
            } else {
                self.main
            }
        } else {
            self.main
        };

        let data = if source.should_thumbnail(settings.prefer_thumbnail, settings.dimensions) {
            // Try to get a thumbnail.
            let media = client.media();
            let request = MediaRequest {
                source: source.source.to_common_media_source(),
                format: MediaFormat::Thumbnail(settings.into()),
            };
            let handle = spawn_tokio!(async move { media.get_media_content(&request, true).await });

            match handle.await.unwrap() {
                Ok(data) => Some(data),
                Err(error) => {
                    warn!("Could not retrieve media thumbnail: {error}");
                    None
                }
            }
        } else {
            None
        };

        // Fallback to downloading the full source.
        let data = if let Some(data) = data {
            data
        } else {
            let media = client.media();
            let request = MediaRequest {
                source: source.source.to_common_media_source(),
                format: MediaFormat::File,
            };

            spawn_tokio!(async move { media.get_media_content(&request, true).await })
                .await
                .unwrap()?
        };

        Ok(save_data_to_tmp_file(&data)?)
    }
}

/// The source of an image.
#[derive(Debug, Clone, Copy)]
pub struct ImageSource<'a> {
    /// The source of the image.
    pub source: MediaSource<'a>,
    /// Information about the image.
    pub info: Option<ImageSourceInfo<'a>>,
}

impl<'a> ImageSource<'a> {
    /// Whether we should try to thumbnail this source for the given requested
    /// dimensions.
    fn should_thumbnail(
        &self,
        prefer_thumbnail: bool,
        thumbnail_dimensions: ImageDimensions,
    ) -> bool {
        if !self.can_be_thumbnailed() {
            return false;
        }

        let dimensions = self.dimensions();

        if prefer_thumbnail && dimensions.is_none() {
            return true;
        }

        dimensions.is_some_and(|d| d.should_resize_for_thumbnail(thumbnail_dimensions))
            || filesize_is_too_big(self.filesize())
    }

    /// Whether this source can be thumbnailed by the media repo.
    ///
    /// Returns `false` in these cases:
    ///
    /// - The image is encrypted, because it is not possible for the media repo
    ///   to make a thumbnail.
    /// - The image uses the SVG format, because media repos usually do not
    ///   accept to create a thumbnail of those.
    fn can_be_thumbnailed(&self) -> bool {
        !self.source.is_encrypted()
            && !self
                .info
                .is_some_and(|i| i.mimetype.is_some_and(|m| m == SVG_CONTENT_TYPE))
    }

    /// The filesize of this source.
    fn filesize(&self) -> Option<u32> {
        self.info.and_then(|i| i.size)
    }

    /// The dimensions of this source.
    fn dimensions(&self) -> Option<ImageDimensions> {
        self.info.and_then(|i| i.dimensions)
    }
}

/// Whether the given filesize is considered too big to be the preferred source
/// to download.
fn filesize_is_too_big(filesize: Option<u32>) -> bool {
    filesize.is_some_and(|s| s > THUMBNAIL_MAX_FILESIZE_THRESHOLD)
}

/// The source of a media file.
#[derive(Debug, Clone, Copy)]
pub enum MediaSource<'a> {
    /// A common media source.
    Common(&'a CommonMediaSource),
    /// The media source of a sticker.
    Sticker(&'a StickerMediaSource),
    /// An MXC URI.
    Uri(&'a OwnedMxcUri),
}

impl<'a> MediaSource<'a> {
    /// Whether this source is encrypted.
    fn is_encrypted(&self) -> bool {
        match self {
            Self::Common(source) => matches!(source, CommonMediaSource::Encrypted(_)),
            Self::Sticker(source) => matches!(source, StickerMediaSource::Encrypted(_)),
            Self::Uri(_) => false,
        }
    }

    /// Get this source as a `CommonMediaSource`.
    fn to_common_media_source(self) -> CommonMediaSource {
        match self {
            Self::Common(source) => source.clone(),
            Self::Sticker(source) => source.clone().into(),
            Self::Uri(uri) => CommonMediaSource::Plain(uri.clone()),
        }
    }
}

impl<'a> From<&'a CommonMediaSource> for MediaSource<'a> {
    fn from(value: &'a CommonMediaSource) -> Self {
        Self::Common(value)
    }
}

impl<'a> From<&'a StickerMediaSource> for MediaSource<'a> {
    fn from(value: &'a StickerMediaSource) -> Self {
        Self::Sticker(value)
    }
}

impl<'a> From<&'a OwnedMxcUri> for MediaSource<'a> {
    fn from(value: &'a OwnedMxcUri) -> Self {
        Self::Uri(value)
    }
}

/// Information about the source of an image.
#[derive(Debug, Clone, Copy, Default)]
pub struct ImageSourceInfo<'a> {
    /// The dimensions of the image.
    dimensions: Option<ImageDimensions>,
    /// The MIME type of the image.
    mimetype: Option<&'a str>,
    /// The file size of the image.
    size: Option<u32>,
}

impl<'a> From<&'a ImageInfo> for ImageSourceInfo<'a> {
    fn from(value: &'a ImageInfo) -> Self {
        Self {
            dimensions: ImageDimensions::from_options(
                value.width.and_then(|u| u.try_into().ok()),
                value.height.and_then(|u| u.try_into().ok()),
            ),
            mimetype: value.mimetype.as_deref(),
            size: value.size.and_then(|u| u.try_into().ok()),
        }
    }
}

impl<'a> From<&'a ThumbnailInfo> for ImageSourceInfo<'a> {
    fn from(value: &'a ThumbnailInfo) -> Self {
        Self {
            dimensions: ImageDimensions::from_options(
                value.width.and_then(|u| u.try_into().ok()),
                value.height.and_then(|u| u.try_into().ok()),
            ),
            mimetype: value.mimetype.as_deref(),
            size: value.size.and_then(|u| u.try_into().ok()),
        }
    }
}

impl<'a> From<&'a AvatarImageInfo> for ImageSourceInfo<'a> {
    fn from(value: &'a AvatarImageInfo) -> Self {
        Self {
            dimensions: ImageDimensions::from_options(
                value.width.and_then(|u| u.try_into().ok()),
                value.height.and_then(|u| u.try_into().ok()),
            ),
            mimetype: value.mimetype.as_deref(),
            size: value.size.and_then(|u| u.try_into().ok()),
        }
    }
}

/// The settings for downloading a thumbnail.
#[derive(Debug, Clone)]
pub struct ThumbnailSettings {
    /// The resquested dimensions of the thumbnail.
    pub dimensions: ImageDimensions,
    /// The method to use to resize the thumbnail.
    pub method: Method,
    /// Whether to request an animated thumbnail.
    pub animated: bool,
    /// Whether we should prefer to get a thumbnail if dimensions are unknown.
    ///
    /// This is particularly useful for avatars where we will prefer to save
    /// bandwidth and memory usage as we download a lot of them and they might
    /// appear several times on the screen. For media messages, we will on the
    /// contrary prefer to download the original content to reduce the space
    /// taken in the media cache.
    pub prefer_thumbnail: bool,
}

impl From<ThumbnailSettings> for MediaThumbnailSettings {
    fn from(value: ThumbnailSettings) -> Self {
        let ThumbnailSettings {
            dimensions,
            method,
            animated,
            ..
        } = value;

        MediaThumbnailSettings {
            size: MediaThumbnailSize {
                method,
                width: dimensions.width.into(),
                height: dimensions.height.into(),
            },
            animated,
        }
    }
}