fastly 0.12.0

Fastly Compute API
Documentation
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
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
//! Interface to the Fastly Image Optimizer.
//!
//! The Fastly [Image Optimizer] is a real-time image transformation and optimization
//! service that caches and serves pixel-optimized, bandwidth-efficient images requested
//! from your origin server.
//!
//! Note that this functionality is in beta. Please reach out to Fastly support before
//! using.
//!
//! This module contains parameters that express transformation options
//! In particular, [`ImageOptimizerOptions`] is used with
//! [`Request::set_image_optimizer`][`crate::http::Request::set_image_optimizer`] or
//! [`Request::with_image_optimizer`][`crate::http::Request::with_image_optimizer`]
//! to enable Image Optimization on a request. See those methods for details on usage.
//!
//! [Image Optimizer]: https://docs.fastly.com/products/image-optimizer
use crate::error::anyhow;
use serde::{Serialize, Serializer};
use serde_repr::*;
use std::fmt;

/// Available regions for image transformation.
#[derive(Debug, Clone)]
pub enum ImageOptimizerRegion {
    /// Apply image optimization in the eastern United States.
    UsEast,
    /// Apply image optimization in the central United States.
    UsCentral,
    /// Apply image optimization in the western United States.
    UsWest,
    /// Apply image optimization in central Europe.
    EuCentral,
    /// Apply image optimization in western Europe.
    EuWest,
    /// Apply image optimization in Asia.
    Asia,
    /// Apply image optimization in Australia.
    Australia,
}

impl Serialize for ImageOptimizerRegion {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        match self {
            ImageOptimizerRegion::UsEast => serializer.serialize_str("us_east"),
            ImageOptimizerRegion::UsCentral => serializer.serialize_str("us_central"),
            ImageOptimizerRegion::UsWest => serializer.serialize_str("us_west"),
            ImageOptimizerRegion::EuCentral => serializer.serialize_str("eu_central"),
            ImageOptimizerRegion::EuWest => serializer.serialize_str("eu_west"),
            ImageOptimizerRegion::Asia => serializer.serialize_str("asia"),
            ImageOptimizerRegion::Australia => serializer.serialize_str("australia"),
        }
    }
}

/// Errors that can arise during construction of Image Optimizer requests.
#[derive(Debug, PartialEq)]
pub enum ImageOptimizerAPIError {
    /// An invalid value was given for a parameter.
    ParameterError(String),

    /// An error occurred during parameter serialization.
    SerializeError,
}

impl ImageOptimizerAPIError {
    pub(crate) fn into_anyhow(self) -> anyhow::Error {
        match self {
            ImageOptimizerAPIError::ParameterError(s) => anyhow!(s),
            ImageOptimizerAPIError::SerializeError => anyhow!("failed to serialize api params"),
        }
    }
}

/// Specifies the desired output encoding for the image.
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all(serialize = "lowercase"))]
pub enum Format {
    /// Automatically use the best format based on browser support and image/transform characteristics.
    Auto,
    /// Convert to AVIF.
    AVIF,
    /// Convert to GIF (Graphics Interchange Format).
    GIF,
    /// Convert to JPEG.
    JPEG,
    /// Convert to JPEGXL.
    JPEGXL,
    /// Convert to MP4.
    MP4,
    /// Convert to PNG (Portable Network Graphics).
    PNG,
    /// Convert to WebP.
    WebP,
}

/// Enables optimizations based on content negotiation.
///
/// This functionality is also possible by setting [ImageOptimizerOptions::format] to
/// [Format::Auto], which will additionally support JPEGXL output.
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all(serialize = "lowercase"))]
pub enum Auto {
    /// If the browser's Accept header indicates compatibility, deliver an AVIF image.
    AVIF,
    /// If the browser's Accept header indicates compatibility, deliver a WebP image.
    WebP,
}

/// Specify a position along an axis in an image.
#[derive(Debug, Clone)]
pub enum PixelsOrPercentage {
    /// Speciy a position in pixels.
    Pixels(u32),
    /// Speciy a position in percentage of the image size.
    Percentage(f64),
}

impl fmt::Display for PixelsOrPercentage {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self {
            PixelsOrPercentage::Pixels(u) => write!(f, "{}", u),
            PixelsOrPercentage::Percentage(p) => write!(f, "{}p", fmt_float(*p)),
        }
    }
}

impl Serialize for PixelsOrPercentage {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        match self {
            PixelsOrPercentage::Pixels(u) => serializer.serialize_u32(*u),
            PixelsOrPercentage::Percentage(p) => {
                let val = format!("{}p", fmt_float(*p));
                serializer.serialize_str(&val)
            }
        }
    }
}

fn fmt_float(v: f64) -> String {
    let nearest_three: f64 = f64::round(1000.0 * v) / 1000.0;
    if nearest_three.fract() > 0.0 {
        format!("{:?}", nearest_three)
    } else {
        format!("{:?}", v as i32)
    }
}

/// Controls cropping behaviour.
#[derive(Debug, Clone)]
pub enum CropMode {
    /// Avoid invalid parameter errors and return an image.
    ///
    /// By default, if the specified cropped region is outside the bounds of the image, then the
    /// transformation will fail with the error "Invalid transformation for requested image:
    /// Invalid crop, region out of bounds". This option will instead deliver the image as an
    /// intersection of the origin image and the specified cropped region. This avoids the error,
    /// but the resulting image may not be of the specified dimensions.
    Safe = 1,
    /// Enable content-aware algorithms to attempt to crop the image to the desired aspect ratio
    /// while intelligently focusing on the most important visual content, including the detection
    /// of faces.
    Smart = 2,
}

/// Specify an area.
#[derive(Debug, Clone)]
pub enum Area {
    /// Specify a width to height ratio.
    AspectRatio((u32, u32)),
    /// Specify a precise number of pixels.
    WidthHeight((PixelsOrPercentage, PixelsOrPercentage)),
}

impl fmt::Display for Area {
    fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
        match self {
            Area::AspectRatio((w, h)) => {
                write!(fmt, "{}:{}", w, h)
            }
            Area::WidthHeight((w, h)) => {
                write!(fmt, "{},{}", w, h)
            }
        }
    }
}

/// Specify a position along an axis in an image.
#[derive(Debug, Clone, Serialize)]
pub enum PointOrOffset {
    /// An offset relative to the top left of the image.
    Point(PixelsOrPercentage),
    /// An offset relative to the center of the image, specified as a percentage of the image size.
    Offset(u32), // percentage
}

impl fmt::Display for PointOrOffset {
    fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
        match self {
            PointOrOffset::Point(p) => {
                write!(fmt, "{}", p)
            }
            PointOrOffset::Offset(u) => {
                write!(fmt, "{}p", u)
            }
        }
    }
}

/// A position within an image.
#[derive(Debug, Clone)]
pub struct Position {
    /// The x-axis parameter.
    pub x: Option<PointOrOffset>,
    /// The y-axis parameter.
    pub y: Option<PointOrOffset>,
}

impl fmt::Display for Position {
    fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
        fn write_point_or_offset(
            fmt: &mut fmt::Formatter,
            axis: &str,
            p: &PointOrOffset,
        ) -> fmt::Result {
            match p {
                PointOrOffset::Point(p) => {
                    write!(fmt, "{}{}", axis, p)
                }
                PointOrOffset::Offset(f) => {
                    write!(fmt, "offset-{}{}", axis, f)
                }
            }
        }

        let mut wrote_x = false;
        if let Some(x) = &self.x {
            wrote_x = true;
            write_point_or_offset(fmt, "x", x)?;
        }

        if let Some(y) = &self.y {
            if wrote_x {
                write!(fmt, ",")?;
            }
            write_point_or_offset(fmt, "y", y)?;
        }
        Ok(())
    }
}

/// Remove pixels from an image.
#[derive(Debug, Clone)]
pub struct Crop {
    /// Desired width and height.
    pub size: Area,
    /// Offset for determing starting position of the cropped region.
    pub position: Option<Position>,
    /// Crop mode to use.
    pub mode: Option<CropMode>,
}

impl Serialize for Crop {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        let mut crop_str = format!("{}", self.size);

        if let Some(pos) = &self.position {
            let pos_str = format!(",{}", pos);
            crop_str.push_str(&pos_str);
        }

        if let Some(mode) = &self.mode {
            match mode {
                CropMode::Safe => crop_str.push_str(",safe"),
                CropMode::Smart => crop_str.push_str(",smart"),
            };
        }

        serializer.serialize_str(&crop_str)
    }
}

/// Parameters for adding or removing pixels from the sides of an image.
#[derive(Debug, Clone)]
pub struct Sides {
    /// Difference for the top of the image.
    pub top: PixelsOrPercentage,
    /// Difference for the right of the image.
    pub right: PixelsOrPercentage,
    /// Difference for the bottom of the image.
    pub bottom: PixelsOrPercentage,
    /// Difference for the left of the image.
    pub left: PixelsOrPercentage,
}

impl Serialize for Sides {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        let sides_str = format!("{},{},{},{}", self.top, self.right, self.bottom, self.left);
        serializer.serialize_str(&sides_str)
    }
}

/// The optimize parameter automatically applies optimal quality
/// compression to produce an output image with as much visual fidelity as
/// possible, while minimizing the file size.
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all(serialize = "lowercase"))]
pub enum OptimizeLevel {
    /// Output image quality will be similar to the input image quality.
    Low = 1,
    /// More optimization is allowed, while attempting to preserve the visual
    /// quality of the input image.
    Medium = 2,
    /// Minor visual artifacts may be visible. This produces the smallest file.
    High = 3,
}

/// The orient parameter controls the cardinal orientation of the image.
#[derive(Debug, Clone, Serialize_repr)]
#[repr(u8)]
pub enum Orientation {
    /// Default to image as-is.
    Default = 1,
    /// Flip the image horizontally.
    FlipHorizontal = 2,
    /// Flip the image horizontally and vertically.
    FlipHorizontalAndVertical = 3,
    /// Flip the image vertically.
    FlipVertical = 4,
    /// Flip the image horizontally, then orient the image left.
    FlipHorizontalOrientLeft = 5,
    /// Orient the image right.
    OrientRight = 6,
    /// Flip the image horizontally, then orient the image right.
    FlipHorizontalOrientRight = 7,
    /// Orient the image left.
    OrientLeft = 8,
}

/// A hexadecimal color specification.
#[derive(Debug, Clone)]
pub struct HexColor {
    /// Amount of red.
    pub r: u8,
    /// Amount of green.
    pub g: u8,
    /// Amount of blue.
    pub b: u8,
    /// Alpha channel parameter.
    ///
    /// This value should be between 0 (fully transparent) and 1 (fully opaque).
    pub a: f32,
}

impl Serialize for HexColor {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        let rgba_str = format!("{},{},{},{:?}", self.r, self.g, self.b, self.a);
        serializer.serialize_str(&rgba_str)
    }
}

/// Identify a rectangular border based on specified color and remove this
/// border from the edges of an image.
#[derive(Debug, Clone)]
pub struct TrimColor {
    /// Indicates what color to trim off.
    pub color: HexColor,
    /// An optional number between 0 and 1 indicating how different a color can
    /// be from the given trim color and still be trimmed.
    ///
    /// This can be used if the background that is being trimmed is not uniform
    /// (all one color). Setting it to 1 will trim everything, as 1 is the
    /// largest possible color difference.
    pub threshold: f32,
}

impl Serialize for TrimColor {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        let trim_color_str = format!(
            "{},{},{},{:?},t{}",
            self.color.r,
            self.color.g,
            self.color.b,
            self.color.a,
            fmt_float(self.threshold.into())
        );
        serializer.serialize_str(&trim_color_str)
    }
}

/// Controls conversion of image to black and white duotone.
#[derive(Debug, Clone)]
pub enum BWMode {
    //e Use [Atkinson dithering].
    ///
    /// [Atkinson dithering]: https://en.wikipedia.org/wiki/Atkinson_dithering
    Atkinson,
    /// DefaultThreshold uses the default threshold value of 49.
    DefaultThreshold,
    /// Threshold can be between 0-100.
    Threshold(u32),
}

impl Serialize for BWMode {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        match self {
            BWMode::Atkinson => serializer.serialize_str("atkinson"),
            BWMode::DefaultThreshold => serializer.serialize_str("threshold"),
            BWMode::Threshold(u) => {
                let threshold_str = format!("threshold,{}", u);
                serializer.serialize_str(&threshold_str)
            }
        }
    }
}

/// Applies a [Gaussian blur] filter to the image.
///
/// [Gaussian blur]: https://en.wikipedia.org/wiki/Gaussian_blur
#[derive(Debug, Clone)]
pub enum BlurMode {
    /// Specify the radius of the blur in pixels.
    Pixels(f64),
    /// Specify the radius of the blur as a percentage of the image size.
    Percentage(f64),
}

impl Serialize for BlurMode {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        match self {
            BlurMode::Pixels(p) => serializer.serialize_f64(*p),
            BlurMode::Percentage(p) => {
                let percent_str = format!("{}p", p);
                serializer.serialize_str(&percent_str)
            }
        }
    }
}

/// Specify the size of the image canvas.
#[derive(Debug, Clone)]
pub struct Canvas {
    /// Specifies the desired width and height.
    pub size: Area,
    /// How to distribute remaining space around the image.
    pub position: Option<Position>,
}

impl Serialize for Canvas {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        let mut canvas_str = format!("{}", self.size);
        if let Some(p) = &self.position {
            let pos_str = format!(",{}", p);
            canvas_str.push_str(&pos_str);
        }

        serializer.serialize_str(&canvas_str)
    }
}

/// The fit parameter controls how the image will be constrained within
/// the provided size (width and height) values, in order to maintain
/// the correct proportions.
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all(serialize = "lowercase"))]
pub enum Fit {
    /// Resize the image to fit entirely within the specified region, making
    /// one dimension smaller if needed.
    Bounds = 1,
    /// Resize the image to entirely cover the specified region, making one
    /// dimension larger if needed.
    Cover = 2,
    /// Resize and crop the image centrally to exactly fit the specified region.
    Crop = 3,
}

/// The level parameter specifies a set of constraints indicating
/// [a degree of required decoder performance][perf] for a profile.
///
/// This option is only used when converting animated GIFs to the MP4 format and when used in
/// conjunction with the profile parameter,
///
/// [perf]: https://en.wikipedia.org/wiki/Advanced_Video_Coding#Levels
#[derive(Debug, Clone)]
pub enum Level {
    /// Level 1.0
    Level1_0,
    /// Level 1.1
    Level1_1,
    /// Level 1.2
    Level1_2,
    /// Level 1.3
    Level1_3,
    /// Level 2.0
    Level2_0,
    /// Level 2.1
    Level2_1,
    /// Level 2.2
    Level2_2,
    /// Level 3.0
    Level3_0,
    /// Level 3.1
    Level3_1,
    /// Level 3.2
    Level3_2,
    /// Level 4.0
    Level4_0,
    /// Level 4.1
    Level4_1,
    /// Level 4.2
    Level4_2,
    /// Level 5.0
    Level5_0,
    /// Level 5.1
    Level5_1,
    /// Level 5.2
    Level5_2,
    /// Level 6.0
    Level6_0,
    /// Level 6.1
    Level6_1,
    /// Level 6.2
    Level6_2,
}

impl Serialize for Level {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        match self {
            Level::Level1_0 => serializer.serialize_str("1.0"),
            Level::Level1_1 => serializer.serialize_str("1.1"),
            Level::Level1_2 => serializer.serialize_str("1.2"),
            Level::Level1_3 => serializer.serialize_str("1.3"),
            Level::Level2_0 => serializer.serialize_str("2.0"),
            Level::Level2_1 => serializer.serialize_str("2.1"),
            Level::Level2_2 => serializer.serialize_str("2.2"),
            Level::Level3_0 => serializer.serialize_str("3.0"),
            Level::Level3_1 => serializer.serialize_str("3.1"),
            Level::Level3_2 => serializer.serialize_str("3.2"),
            Level::Level4_0 => serializer.serialize_str("4.0"),
            Level::Level4_1 => serializer.serialize_str("4.1"),
            Level::Level4_2 => serializer.serialize_str("4.2"),
            Level::Level5_0 => serializer.serialize_str("5.0"),
            Level::Level5_1 => serializer.serialize_str("5.1"),
            Level::Level5_2 => serializer.serialize_str("5.2"),
            Level::Level6_0 => serializer.serialize_str("6.0"),
            Level::Level6_1 => serializer.serialize_str("6.1"),
            Level::Level6_2 => serializer.serialize_str("6.2"),
        }
    }
}

/// Controls what metadata to preserve in images.
///
/// By default, the Image Optimizer will remove all metadata in an image.
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all(serialize = "lowercase"))]
pub enum Metadata {
    /// Preserve copyright notice, creator, credit line, licensor, and web statement of rights
    /// fields.
    Copyright,
}

/// The profile parameter controls which features the video encoder can use based on a target class
/// of application for decoding the specific video bitstream.
///
/// This option is only used when converting animated GIFs to the MP4 format and when used in
/// conjunction with the level parameter,
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all(serialize = "lowercase"))]
pub enum Profile {
    /// The profile recommended for video conferencing and mobile applications.
    Baseline,
    /// The profile recommended for standard-definition broadcasts.
    Main,
    /// The profile recommended for high-definition broadcasts.
    High,
}

/// Enables control over the resizing filter used to generate a new image with a higher or lower
/// number of pixels.
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all(serialize = "lowercase"))]
pub enum ResizeAlgorithm {
    /// Uses the value of nearby translated pixel values.
    Nearest,
    /// Uses an average of a 2x2 environment of pixels.
    Bilinear,
    /// Uses an average of a 4x4 environment of pixels, weighing the innermost pixels higher.
    Bicubic,
    /// Uses the Lanczos filter to increase the ability to detect edges and linear features within
    /// an image and uses sinc resampling to provide the best possible reconstruction.
    Lanczos2,
    /// Lanczos3 uses a better approximation of the sinc resampling function.
    Lanczos3,
}

/// Options for increasing the definition of the edges of objects in an image.
#[derive(Debug, Clone)]
pub struct Sharpen {
    /// Amount parameter for the unsharp mask.
    ///
    /// This should be a value between 0 and 10.
    pub amount: u8,
    /// Radius parameter for the unsharp mask.
    ///
    /// This should be a value between 0.5 and 1000.
    pub radius: f32,
    /// Threshold parameter for the unsharp mask.
    ///
    /// This should be a value between 0 and 255.
    pub threshold: u8,
}

impl Serialize for Sharpen {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        let sharpen_str = format!(
            "a{},r{},t{}",
            self.amount,
            fmt_float(self.radius.into()),
            self.threshold
        );
        serializer.serialize_str(&sharpen_str)
    }
}

/// Features that are disabled by default, but can be requested to be enabled.
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all(serialize = "lowercase"))]
pub enum EnableOpt {
    /// Allow images to be resized such that the output image's dimensions are
    /// larger than the source image.
    Upscale,
}

/// ImageOptimizerOptions contains options that correspond to the [public API].
///
/// [public API]: https://www.fastly.com/documentation/reference/io/
#[derive(Debug, Default, Clone, Serialize)]
#[non_exhaustive]
pub struct ImageOptimizerOptions {
    /// Indicates where image transformations will occur. Must be set.
    ///
    /// See [`ImageOptimizerRegion`] for available options. The chosen region should be close to
    /// your origin.
    pub region: Option<ImageOptimizerRegion>,
    /// If true, preserves query parameters not belonging to the
    /// Image Optimizer API when requesting the origin image.
    pub preserve_query_string_on_origin_request: Option<bool>,
    /// Requests an output format based on the `Accept` header.
    pub auto: Option<Auto>,
    /// Sets a background color when replacing transparent pixels
    /// or with `pad` or `canvas`.
    #[serde(rename = "bg-color")]
    pub bg_color: Option<HexColor>,
    /// Blurs the image.
    pub blur: Option<BlurMode>,
    /// Adjusts image brightness.
    pub brightness: Option<i32>, // -100 to 100
    /// Converts image to black and white duotone.
    pub bw: Option<BWMode>,
    /// Adds a canvas surrounding the image.
    pub canvas: Option<Canvas>,
    /// Adjusts image contrast.
    pub contrast: Option<i32>, // -100 to 100
    /// Crops the image.
    pub crop: Option<Crop>,
    /// Ratio between physical and logical pixels, a float between 0-10.
    ///
    /// Adjusts any resize requests according to this ratio.
    pub dpr: Option<f32>,
    /// Allows for various image transformations to occur,
    /// particularly upscaling images.
    pub enable: Option<EnableOpt>,
    /// Describes how the image should fit within the requested dimensions.
    pub fit: Option<Fit>,
    /// Re-encodes the image to a given output format.
    pub format: Option<Format>,
    /// Request a single frame for an animated image.
    ///
    /// Currently only supported for animated GIFs.
    pub frame: Option<u32>,
    /// Adjusts image height.
    pub height: Option<PixelsOrPercentage>,
    /// For use with GIF to MP4 conversions.
    ///
    /// See <https://www.fastly.com/documentation/reference/io/level/> for detailed information.
    pub level: Option<Level>,
    /// Preserves metadata on the input image.
    pub metadata: Option<Metadata>,
    /// Attempts to select an output quality to optimize the image.
    pub optimize: Option<OptimizeLevel>,
    /// Controls how the image will be oriented.
    pub orient: Option<Orientation>,
    /// Adds pixels surrounding the image.
    pub pad: Option<Sides>,
    /// Applies the crop instruction before all other parameters.
    pub precrop: Option<Crop>,
    /// For use with GIF to MP4 conversions.
    ///
    /// See <https://www.fastly.com/documentation/reference/io/level/> for detailed information.
    pub profile: Option<Profile>,
    /// Request an output quality.
    pub quality: Option<u32>,
    /// Specify which algorithm to use when resizing an image.
    #[serde(rename = "resize-filter")]
    pub resize_filter: Option<ResizeAlgorithm>,
    /// Adjust image saturation.
    pub saturation: Option<i32>, // -100 to 100
    /// Applies an unsharp mask to the image.
    pub sharpen: Option<Sharpen>,
    /// Removes pixels from the image on all sides.
    pub trim: Option<Sides>,
    #[serde(rename = "trim-color")]
    /// Trims the image on all sides based on a given color.
    pub trim_color: Option<TrimColor>,
    /// Adjusts image width.
    pub width: Option<PixelsOrPercentage>,
}

impl ImageOptimizerOptions {
    /// Create ImageOptimizerOptions for the specified region. It is recommended to pick
    /// a region closest to your origin that serves images.
    ///
    /// See [`Request::set_image_optimizer`][`crate::Request::set_image_optimizer()`] for example usage.
    pub fn from_region(region: ImageOptimizerRegion) -> Self {
        ImageOptimizerOptions {
            region: Some(region),
            ..Default::default()
        }
    }

    pub(crate) fn to_claims_opts(&self) -> Result<String, ImageOptimizerAPIError> {
        self.validate_params()?;

        serde_urlencoded::to_string(self).map_err(|_| ImageOptimizerAPIError::SerializeError)
    }

    fn validate_params(&self) -> Result<(), ImageOptimizerAPIError> {
        if self.region.is_none() {
            return Err(ImageOptimizerAPIError::ParameterError(
                "region parameter on ImageOptimizerOptions must be set".to_string(),
            ));
        }

        if let Some(bg) = &self.bg_color {
            if bg.a < 0.0 || bg.a > 1.0 {
                return Err(ImageOptimizerAPIError::ParameterError(
                    "alpha must be between 0 and 1, inclusive".to_string(),
                ));
            }
        }

        if let Some(b) = self.brightness {
            if b < -100 || b > 100 {
                return Err(ImageOptimizerAPIError::ParameterError(
                    "brightness must be between -100 and 100, inclusive".to_string(),
                ));
            }
        }

        if let Some(c) = self.contrast {
            if c < -100 || c > 100 {
                return Err(ImageOptimizerAPIError::ParameterError(
                    "contrast must be between -100 and 100, inclusive".to_string(),
                ));
            }
        }

        if let Some(dpr) = self.dpr {
            if dpr < 0.0 || dpr > 10.0 {
                return Err(ImageOptimizerAPIError::ParameterError(
                    "dpr must be between 0 and 10, inclusive".to_string(),
                ));
            }
        }

        if let Some(q) = self.quality {
            if q > 100 {
                return Err(ImageOptimizerAPIError::ParameterError(
                    "quality must be between 0 and 100, inclusive".to_string(),
                ));
            }
        }

        if let Some(s) = self.saturation {
            if s < -100 || s > 100 {
                return Err(ImageOptimizerAPIError::ParameterError(
                    "saturation must be between -100 and 100, inclusive".to_string(),
                ));
            }
        }

        if let Some(s) = &self.sharpen {
            if s.amount > 10 {
                return Err(ImageOptimizerAPIError::ParameterError(
                    "sharpen amount must be between 0 and 10, inclusive".to_string(),
                ));
            }

            if s.radius < 0.5 || s.radius > 1000.0 {
                return Err(ImageOptimizerAPIError::ParameterError(
                    "sharpen radius must be between 0.5 and 1000, inclusive".to_string(),
                ));
            }
        }

        if let Some(tc) = &self.trim_color {
            if tc.color.a < 0.0 || tc.color.a > 1.0 {
                return Err(ImageOptimizerAPIError::ParameterError(
                    "alpha must be between 0 and 1, inclusive".to_string(),
                ));
            }

            if tc.threshold < 0.0 || tc.threshold > 1.0 {
                return Err(ImageOptimizerAPIError::ParameterError(
                    "threshold must be between 0 and 1, inclusive".to_string(),
                ));
            }
        }

        return Ok(());
    }
}

#[cfg(test)]
mod image_optimizer_options_test {
    use super::*;

    fn test_query_params(options: &ImageOptimizerOptions, expected: &str) {
        match serde_urlencoded::to_string(options) {
            Ok(qp) => assert_eq!(qp, expected),
            Err(e) => panic!("got unexpected error: {e}"),
        }
    }

    #[test]
    fn query_params_are_valid() {
        let mut options = ImageOptimizerOptions::from_region(ImageOptimizerRegion::UsEast);
        test_query_params(&options, "region=us_east");

        options.width = Some(PixelsOrPercentage::Percentage(50.0));
        test_query_params(&options, "region=us_east&width=50p");
        options.width = None;

        options.auto = Some(Auto::WebP);
        test_query_params(&options, "region=us_east&auto=webp");
        options.auto = None;

        options.bg_color = Some(HexColor {
            r: 0,
            g: 255,
            b: 0,
            a: 0.3,
        });
        test_query_params(&options, "region=us_east&bg-color=0%2C255%2C0%2C0.3");
        options.bg_color = None;

        options.blur = Some(BlurMode::Pixels(50.0));
        test_query_params(&options, "region=us_east&blur=50.0");

        options.blur = Some(BlurMode::Percentage(0.8));
        test_query_params(&options, "region=us_east&blur=0.8p");
        options.blur = None;

        options.brightness = Some(-50);
        test_query_params(&options, "region=us_east&brightness=-50");
        options.brightness = None;

        options.bw = Some(BWMode::Threshold(10));
        test_query_params(&options, "region=us_east&bw=threshold%2C10");
        options.bw = None;

        options.contrast = Some(-5);
        test_query_params(&options, "region=us_east&contrast=-5");
        options.contrast = None;

        options.dpr = Some(3.2);
        test_query_params(&options, "region=us_east&dpr=3.2");
        options.dpr = None;

        options.enable = Some(EnableOpt::Upscale);
        test_query_params(&options, "region=us_east&enable=upscale");
        options.enable = None;

        options.format = Some(Format::JPEGXL);
        test_query_params(&options, "region=us_east&format=jpegxl");
        options.format = None;

        options.frame = Some(1);
        test_query_params(&options, "region=us_east&frame=1");
        options.frame = None;

        options.height = Some(PixelsOrPercentage::Percentage(80.0));
        test_query_params(&options, "region=us_east&height=80p");
        options.height = None;

        // level and profile are used for MP4 transformations.
        options.level = Some(Level::Level2_0);
        options.format = Some(Format::MP4);
        options.profile = Some(Profile::High);
        test_query_params(&options, "region=us_east&format=mp4&level=2.0&profile=high");
        options.level = None;
        options.format = None;
        options.profile = None;

        options.metadata = Some(Metadata::Copyright);
        test_query_params(&options, "region=us_east&metadata=copyright");
        options.metadata = None;

        options.optimize = Some(OptimizeLevel::High);
        test_query_params(&options, "region=us_east&optimize=high");
        options.optimize = None;

        options.orient = Some(Orientation::FlipVertical);
        test_query_params(&options, "region=us_east&orient=4");
        options.orient = None;

        options.pad = Some(Sides {
            top: PixelsOrPercentage::Percentage(10.0),
            right: PixelsOrPercentage::Percentage(10.0),
            bottom: PixelsOrPercentage::Percentage(10.0),
            left: PixelsOrPercentage::Percentage(10.0),
        });
        test_query_params(&options, "region=us_east&pad=10p%2C10p%2C10p%2C10p");
        options.pad = None;

        options.resize_filter = Some(ResizeAlgorithm::Lanczos3);
        test_query_params(&options, "region=us_east&resize-filter=lanczos3");
        options.resize_filter = None;

        options.sharpen = Some(Sharpen {
            amount: 5,
            radius: 2.0,
            threshold: 1,
        });
        test_query_params(&options, "region=us_east&sharpen=a5%2Cr2%2Ct1");
        options.sharpen = None;

        options.trim = Some(Sides {
            top: PixelsOrPercentage::Percentage(20.5555),
            right: PixelsOrPercentage::Percentage(33.3333),
            bottom: PixelsOrPercentage::Percentage(20.555),
            left: PixelsOrPercentage::Percentage(33.3333),
        });
        test_query_params(
            &options,
            "region=us_east&trim=20.556p%2C33.333p%2C20.555p%2C33.333p",
        );
        options.trim = None;

        options.trim_color = Some(TrimColor {
            color: HexColor {
                r: 255,
                g: 0,
                b: 0,
                a: 1.0,
            },
            threshold: 0.5,
        });
        test_query_params(
            &options,
            "region=us_east&trim-color=255%2C0%2C0%2C1.0%2Ct0.5",
        );
    }

    #[test]
    fn canvas_to_string_is_valid() {
        let mut options = ImageOptimizerOptions::from_region(ImageOptimizerRegion::UsEast);
        let mut canvas = Canvas {
            size: Area::WidthHeight((
                PixelsOrPercentage::Pixels(200),
                PixelsOrPercentage::Pixels(200),
            )),
            position: None,
        };
        options.canvas = Some(canvas.clone());
        test_query_params(&options, "region=us_east&canvas=200%2C200");

        let mut test_position = Position {
            x: Some(PointOrOffset::Point(PixelsOrPercentage::Percentage(50.0))),
            y: Some(PointOrOffset::Point(PixelsOrPercentage::Percentage(50.0))),
        };
        canvas.position = Some(test_position);
        options.canvas = Some(canvas.clone());
        test_query_params(&options, "region=us_east&canvas=200%2C200%2Cx50p%2Cy50p");

        test_position = Position {
            x: Some(PointOrOffset::Offset(30)),
            y: Some(PointOrOffset::Offset(20)),
        };
        canvas.position = Some(test_position);
        options.canvas = Some(canvas.clone());
        test_query_params(
            &options,
            "region=us_east&canvas=200%2C200%2Coffset-x30%2Coffset-y20",
        );

        canvas.size = Area::AspectRatio((16, 9));
        options.canvas = Some(canvas.clone());
        test_query_params(
            &options,
            "region=us_east&canvas=16%3A9%2Coffset-x30%2Coffset-y20",
        );
    }

    #[test]
    fn crop_to_string_is_valid() {
        let mut options = ImageOptimizerOptions::from_region(ImageOptimizerRegion::UsEast);
        let mut crop = Crop {
            size: Area::AspectRatio((1, 1)),
            position: None,
            mode: None,
        };
        options.crop = Some(crop.clone());
        test_query_params(&options, "region=us_east&crop=1%3A1");

        crop.mode = Some(CropMode::Safe);
        options.crop = Some(crop.clone());
        test_query_params(&options, "region=us_east&crop=1%3A1%2Csafe");

        crop.position = Some(Position {
            x: Some(PointOrOffset::Point(PixelsOrPercentage::Pixels(30))),
            y: None,
        });
        options.crop = Some(crop.clone());
        test_query_params(&options, "region=us_east&crop=1%3A1%2Cx30%2Csafe");

        crop.position = Some(Position {
            x: Some(PointOrOffset::Point(PixelsOrPercentage::Percentage(30.0))),
            y: Some(PointOrOffset::Point(PixelsOrPercentage::Percentage(20.0))),
        });
        options.crop = Some(crop.clone());
        test_query_params(&options, "region=us_east&crop=1%3A1%2Cx30p%2Cy20p%2Csafe");

        crop.position = Some(Position {
            x: Some(PointOrOffset::Point(PixelsOrPercentage::Pixels(30))),
            y: Some(PointOrOffset::Point(PixelsOrPercentage::Percentage(20.0))),
        });
        options.crop = Some(crop.clone());
        test_query_params(&options, "region=us_east&crop=1%3A1%2Cx30%2Cy20p%2Csafe");

        crop.position = Some(Position {
            x: Some(PointOrOffset::Offset(30)),
            y: None,
        });
        options.crop = Some(crop.clone());
        test_query_params(&options, "region=us_east&crop=1%3A1%2Coffset-x30%2Csafe");

        crop.position = Some(Position {
            x: Some(PointOrOffset::Offset(30)),
            y: Some(PointOrOffset::Offset(15)),
        });
        options.crop = Some(crop.clone());
        test_query_params(
            &options,
            "region=us_east&crop=1%3A1%2Coffset-x30%2Coffset-y15%2Csafe",
        );

        options.fit = Some(Fit::Bounds);
        test_query_params(
            &options,
            "region=us_east&crop=1%3A1%2Coffset-x30%2Coffset-y15%2Csafe&fit=bounds",
        );
        options.fit = None;

        options.crop = None;
        // precrop has the same syntax as crop
        options.precrop = Some(crop);
        test_query_params(
            &options,
            "region=us_east&precrop=1%3A1%2Coffset-x30%2Coffset-y15%2Csafe",
        );
    }

    #[test]
    fn invalid_params() {
        let mut options = ImageOptimizerOptions::default();
        match options.validate_params() {
            Ok(_) => panic!("expected error"),
            Err(e) => assert_eq!(
                e,
                ImageOptimizerAPIError::ParameterError(
                    "region parameter on ImageOptimizerOptions must be set".to_string()
                )
            ),
        }
        options.region = Some(ImageOptimizerRegion::UsEast);

        options.sharpen = Some(Sharpen {
            amount: 5,
            radius: 0.2,
            threshold: 1,
        });

        match options.validate_params() {
            Ok(_) => panic!("expected error"),
            Err(e) => assert_eq!(
                e,
                ImageOptimizerAPIError::ParameterError(
                    "sharpen radius must be between 0.5 and 1000, inclusive".to_string()
                )
            ),
        }

        options.sharpen = None;

        options.dpr = Some(11.0);
        match options.validate_params() {
            Ok(_) => panic!("expected error"),
            Err(e) => assert_eq!(
                e,
                ImageOptimizerAPIError::ParameterError(
                    "dpr must be between 0 and 10, inclusive".to_string()
                )
            ),
        }
    }
}