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
use crate::{error, LoadPathPattern, Result};
use indexmap::{IndexMap, IndexSet};
use ommui_string_patterns::{
    freetextstring, freetextstring_maybe_empty, idstring,
    idstring_maybe_empty,
};
use snafu::{OptionExt, ResultExt};
use std::path::Path;
use uuid::Uuid;
use {chrono, ommui_file_loading};

#[cfg(feature = "filesystem")]
pub mod filesystem;

#[cfg(feature = "client")]
pub mod client;

pub mod handle;

mod loadable_device;
mod storable_device;

pub use self::loadable_device::LoadableDevice;
pub use self::storable_device::StorableDevice;

#[derive(Clone, Debug)]
pub struct Measurement {
    pub curves: IndexMap<String, Curve>,
    pub metadata: MeasurementMetadata,
    pub results: IndexMap<String, Option<f64>>,
}

#[derive(Clone, Debug)]
pub struct Sample {
    pub measurements: IndexMap<usize, Measurement>,
    pub metadata: SampleMetadata,
}

#[derive(Clone, Debug)]
pub struct Description {
    pub device: DeviceDescription,
    pub system_profiles: IndexMap<Uuid, ProfileDescription>,
    pub user_profiles: IndexMap<Uuid, ProfileDescription>,
    pub samplings: IndexMap<String, Sampling>,
    pub units: IndexMap<String, UnitDescription>,
    pub translations: IndexMap<String, IndexMap<String, String>>,
}

pub type Translation = IndexMap<String, String>;
pub type DirectoryListing = IndexMap<String, DirectoryListingEntry>;
pub type MeasurementResults = IndexMap<String, Option<f64>>;
pub type Icon = String;

impl<T: std::cmp::Eq + std::hash::Hash + std::str::FromStr> LoadPathPattern
    for IndexSet<T>
{
    fn load_path_pattern(pattern: &str) -> Result<Self> {
        Ok(ommui_file_loading::load_directory_listing(pattern)
            .context(error::OmmuiFileLoading)?)
    }

    fn load_path_pattern_from_dir<P: AsRef<Path>>(
        dir: P,
        pattern: &str,
    ) -> Result<Self> {
        let s = dir.as_ref().to_str().context(error::InvalidFilePath {
            file_path: dir.as_ref().to_string_lossy().to_string(),
        })?;
        let pattern = format!(
            "{}/{}",
            s.trim_end_matches(|c| c == std::path::MAIN_SEPARATOR),
            pattern
        );
        Self::load_path_pattern(&pattern)
    }
}

#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct DeviceId {
    #[serde(with = "freetextstring")]
    pub serial_number: String,

    pub device_uuid: Uuid,
}

#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct DeviceDescription {
    #[serde(rename = "_caption", with = "freetextstring")]
    pub caption: String,

    #[serde(with = "freetextstring")]
    pub manufacturer: String,

    #[serde(with = "freetextstring")]
    pub model_number: String,

    #[serde(with = "freetextstring")]
    pub revision: String,

    #[serde(with = "idstring")]
    pub icon_id: String,

    pub uuid: Uuid,
}

#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct ProfileDescription {
    #[serde(with = "idstring")]
    pub sampling_id: String,

    #[serde(rename = "_caption", with = "freetextstring")]
    pub caption: String,

    #[serde(rename = "_description", with = "freetextstring")]
    pub description: String,

    // TODO: verify that the key is an idstring
    #[serde(default, skip_serializing_if = "IndexMap::is_empty")]
    pub parameters: IndexMap<String, ProfileParameterDescription>,

    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub results: Vec<ResultReference>,

    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub curves: Vec<ProfileCurveDescription>,

    pub translatable: bool,

    #[serde(default, skip_serializing_if = "Uuid::is_nil")]
    pub parent: Uuid,
}

#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct ProfileCurveDescription {
    pub axes: ProfileCoordinateSystem,

    #[serde(with = "idstring")]
    pub curve_id: String,
}

#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct ProfileAxisDescription {
    #[serde(with = "idstring")]
    pub representation: String,
}

#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
#[serde(rename_all = "camelCase")]
pub enum ParameterMode {
    ChangeableWithDefaultValue,
    ChangeableWithRememberedValue,
    ChangeableWithFixedValue,
    FixedValue,
    FixedHiddenValue,
}

impl ParameterMode {
    pub fn is_hidden(&self) -> bool {
        match *self {
            ParameterMode::ChangeableWithDefaultValue
            | ParameterMode::ChangeableWithRememberedValue
            | ParameterMode::ChangeableWithFixedValue
            | ParameterMode::FixedValue => false,
            ParameterMode::FixedHiddenValue => true,
        }
    }

    pub fn is_remembered(&self) -> bool {
        match *self {
            ParameterMode::ChangeableWithRememberedValue => true,
            ParameterMode::ChangeableWithDefaultValue
            | ParameterMode::ChangeableWithFixedValue
            | ParameterMode::FixedValue
            | ParameterMode::FixedHiddenValue => false,
        }
    }
}

#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
#[serde(rename_all = "camelCase", untagged)]
pub enum Parameter {
    Numeric(f64),
    Boolean(bool),
    // TODO: verify that the value is an idstring
    Enumeration(String),
}

#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
#[serde(rename_all = "camelCase")]
pub enum ParameterType {
    Numeric,
    Boolean,
    Enumeration,
}

pub trait HasParameterType {
    fn parameter_type(&self) -> ParameterType;
}

impl HasParameterType for Parameter {
    fn parameter_type(&self) -> ParameterType {
        match self {
            Parameter::Numeric(_) => ParameterType::Numeric,
            Parameter::Boolean(_) => ParameterType::Boolean,
            Parameter::Enumeration(_) => ParameterType::Enumeration,
        }
    }
}

#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
#[serde(rename_all = "camelCase", untagged)]
pub enum ProfileParameterDescription {
    Numeric(NumericProfileParameterDescription),
    Boolean(BooleanProfileParameterDescription),
    Enumeration(EnumerationProfileParameterDescription),
}

impl HasParameterType for ProfileParameterDescription {
    fn parameter_type(&self) -> ParameterType {
        use self::ProfileParameterDescription as D;
        match self {
            D::Numeric(_) => ParameterType::Numeric,
            D::Boolean(_) => ParameterType::Boolean,
            D::Enumeration(_) => ParameterType::Enumeration,
        }
    }
}

#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct NumericProfileParameterDescription {
    pub value: f64,

    #[serde(
        with = "idstring_maybe_empty",
        default,
        skip_serializing_if = "String::is_empty"
    )]
    pub representation: String,

    pub mode: ParameterMode,
}

#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct BooleanProfileParameterDescription {
    pub value: bool,
    pub mode: ParameterMode,
}

#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct EnumerationProfileParameterDescription {
    pub value: String,
    pub mode: ParameterMode,
}

#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct SampleMetadata {
    pub profile: Uuid,

    // TODO: verify that the key is an idstring
    #[serde(default, skip_serializing_if = "IndexMap::is_empty")]
    pub parameters: IndexMap<String, Parameter>,

    pub uuid: Uuid,

    #[serde(
        with = "freetextstring",
        default,
        skip_serializing_if = "String::is_empty"
    )]
    pub identifier: String,

    pub source: Source,
}

#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct MeasurementMetadata {
    pub active: bool,
    pub timestamp: chrono::DateTime<chrono::offset::Utc>,
    // TODO: verify that the key is an idstring
    #[serde(default, skip_serializing_if = "IndexMap::is_empty")]
    pub properties: IndexMap<String, Parameter>,
}

#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct Sampling {
    #[serde(rename = "_caption", with = "freetextstring")]
    pub caption: String,
    // TODO: verify that the key is an idstring
    pub results: IndexMap<String, ResultDescription>,
    // TODO: verify that the key is an idstring
    #[serde(default, skip_serializing_if = "IndexMap::is_empty")]
    pub curves: IndexMap<String, CurveDescription>,
    // TODO: verify that the key is an idstring
    #[serde(default, skip_serializing_if = "IndexMap::is_empty")]
    pub parameters: IndexMap<String, ParameterDescription>,
    // TODO: verify that the key is an idstring
    #[serde(default, skip_serializing_if = "IndexMap::is_empty")]
    pub properties: IndexMap<String, ParameterDescription>,

    #[serde(with = "idstring")]
    pub icon_id: String,
}

#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct ResultDescription {
    #[serde(rename = "_caption", with = "freetextstring")]
    pub caption: String,

    #[serde(rename = "_shortCaption", with = "freetextstring")]
    pub short_caption: String,

    pub unit: UnitReference,

    // TODO: limit range
    pub resolution: f64,
}

#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct BooleanParameterDescription {
    #[serde(rename = "_caption", with = "freetextstring")]
    pub caption: String,

    // TODO: create short freetextstring
    #[serde(rename = "_shortCaption", with = "freetextstring")]
    pub short_caption: String,

    #[serde(rename = "_valueCaptionTrue", with = "freetextstring")]
    pub value_caption_true: String,

    #[serde(rename = "_valueCaptionFalse", with = "freetextstring")]
    pub value_caption_false: String,

    pub affects_sampling_job: bool,
}

#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct NumericParameterDescription {
    #[serde(rename = "_caption", with = "freetextstring")]
    pub caption: String,

    // TODO: create short freetextstring
    #[serde(rename = "_shortCaption", with = "freetextstring")]
    pub short_caption: String,

    pub unit: UnitReference,

    // TODO: limit range
    pub resolution: f64,

    // TODO: limit range
    pub maximum: f64,

    // TODO: limit range
    pub minimum: f64,

    pub affects_sampling_job: bool,
}

#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct EnumerationParameterDescription {
    #[serde(rename = "_caption", with = "freetextstring")]
    pub caption: String,

    // TODO: create short freetextstring
    #[serde(rename = "_shortCaption", with = "freetextstring")]
    pub short_caption: String,

    // TODO: verify that the key is an idstring
    // TODO: verify that at least one entry is present
    pub enumeration_values: IndexMap<String, EnumerationValueDescription>,

    pub affects_sampling_job: bool,
}

#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
#[serde(rename_all = "PascalCase", tag = "type")]
pub enum ParameterDescription {
    #[serde(rename_all = "camelCase")]
    Numeric(NumericParameterDescription),

    #[serde(rename_all = "camelCase")]
    Boolean(BooleanParameterDescription),

    #[serde(rename_all = "camelCase")]
    Enumeration(EnumerationParameterDescription),
}

impl HasParameterType for ParameterDescription {
    fn parameter_type(&self) -> ParameterType {
        use self::ParameterDescription as D;
        match self {
            D::Numeric(_) => ParameterType::Numeric,
            D::Boolean(_) => ParameterType::Boolean,
            D::Enumeration(_) => ParameterType::Enumeration,
        }
    }
}

#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct EnumerationValueDescription {
    #[serde(rename = "_caption", with = "freetextstring")]
    pub caption: String,

    #[serde(rename = "_shortCaption", with = "freetextstring")]
    pub short_caption: String,

    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub value: Option<f64>,
}

#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct Curve {
    pub points: Vec<Vec<f64>>,

    // TODO: verify that the key is an idstring
    #[serde(default, skip_serializing_if = "IndexMap::is_empty")]
    pub markers: IndexMap<String, Vec<f64>>,
}

#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct CurveDescription {
    #[serde(rename = "_caption", with = "freetextstring")]
    pub caption: String,

    // TODO: create short freetextstring
    #[serde(rename = "_shortCaption", with = "freetextstring")]
    pub short_caption: String,

    pub coordinate_system: CoordinateSystemDescription,

    #[serde(default, skip_serializing_if = "IndexMap::is_empty")]
    pub markers: IndexMap<String, CurveMarkerDescription>,
}

#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct Cartesian2dCoordinateSystemDescription {
    pub x: AxisDescription,
    pub y: AxisDescription,
}

#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct PolarCoordinateSystemDescription {
    pub angle: AxisDescription,
    pub radius: AxisDescription,
}

#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
#[serde(rename_all = "PascalCase", tag = "type")]
pub enum CoordinateSystemDescription {
    #[serde(rename_all = "camelCase")]
    Cartesian2d(Cartesian2dCoordinateSystemDescription),

    #[serde(rename_all = "camelCase")]
    Polar(PolarCoordinateSystemDescription),
}

#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
#[serde(rename_all = "camelCase")]
pub enum CoordinateSystem {
    Cartesian2d,
    Polar,
}

pub trait HasCoordinateSystem {
    fn coordinate_system(&self) -> CoordinateSystem;
}

impl HasCoordinateSystem for CoordinateSystemDescription {
    fn coordinate_system(&self) -> CoordinateSystem {
        use self::CoordinateSystem as C;
        use self::CoordinateSystemDescription as D;
        match self {
            D::Cartesian2d(_) => C::Cartesian2d,
            D::Polar(_) => C::Polar,
        }
    }
}

#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
#[serde(rename_all = "camelCase", untagged)]
pub enum ProfileCoordinateSystem {
    Cartesian2d(ProfileCartesian2d),
    Polar(ProfilePolar),
}

impl HasCoordinateSystem for ProfileCoordinateSystem {
    fn coordinate_system(&self) -> CoordinateSystem {
        use self::CoordinateSystem as C;
        use self::ProfileCoordinateSystem as P;
        match self {
            P::Cartesian2d(_) => C::Cartesian2d,
            P::Polar(_) => C::Polar,
        }
    }
}

#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct ProfileCartesian2d {
    pub x: ProfileAxisDescription,
    pub y: ProfileAxisDescription,
}

#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct ProfilePolar {
    pub angle: ProfileAxisDescription,
    pub radius: ProfileAxisDescription,
}

#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct AxisDescription {
    #[serde(rename = "_caption", with = "freetextstring")]
    pub caption: String,

    // TODO: create short freetextstring
    #[serde(rename = "_shortCaption", with = "freetextstring")]
    pub short_caption: String,

    pub unit: UnitReference,

    // TODO: limit range
    pub resolution: f64,
}

#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct CurveMarkerDescription {
    #[serde(rename = "_caption", with = "freetextstring")]
    pub caption: String,
}

#[derive(Default, Serialize, Deserialize, Debug, Clone, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct DirectoryListingEntry {
    #[serde(
        with = "freetextstring",
        default,
        skip_serializing_if = "String::is_empty"
    )]
    pub description: String,

    #[serde(
        with = "freetextstring_maybe_empty",
        default,
        skip_serializing_if = "String::is_empty"
    )]
    pub identifier: String,

    #[serde(default, skip_serializing_if = "Uuid::is_nil")]
    pub profile: Uuid,
}

#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
#[serde(rename_all = "camelCase")]
pub enum Source {
    Measurement,
    Demo,
}

#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct UnitDescription {
    pub representations: IndexMap<String, UnitRepresentationDescription>,
}

#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct UnitRepresentationDescription {
    #[serde(rename = "_caption", with = "freetextstring_maybe_empty")]
    pub caption: String,

    // TODO: create short freetextstring
    #[serde(
        rename = "_shortCaption",
        with = "freetextstring_maybe_empty"
    )]
    pub short_caption: String,

    pub factor: f64,

    pub offset: f64,

    pub measurement_system: MeasurementSystem,
}

impl UnitRepresentationDescription {
    pub fn raw_to_representation(&self, v: f64) -> f64 {
        (v - self.offset) / self.factor
    }
    pub fn representation_to_raw(&self, v: f64) -> f64 {
        v * self.factor + self.offset
    }
    pub fn raw_to_representation_relative(&self, v: f64) -> f64 {
        v / self.factor
    }
    pub fn representation_to_raw_relative(&self, v: f64) -> f64 {
        v * self.factor
    }
    /// Calculate the number of decimal places required for printing
    /// a value in a resolution.
    /// The resolution is in raw number scale, not converted yet.
    pub fn decimal_places(&self, resolution: f64) -> usize {
        let resolution = self.raw_to_representation_relative(resolution);
        let original = format!("{}", resolution);
        const MAX_PLACES: usize = 12usize;
        for places in 0usize..=MAX_PLACES {
            let rounded = format!("{:.*}", places, resolution);
            if rounded == original {
                return places;
            }
        }
        MAX_PLACES
    }
    /// Convert a number to the representation and format it for
    /// human-readable output with the required resolution.
    /// The resolution is in raw number scale, not converted yet.
    pub fn format(&self, v: f64, resolution: f64) -> String {
        format!(
            "{:.*}",
            self.decimal_places(resolution),
            self.raw_to_representation(v)
        )
    }
}

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

    #[test]
    fn decimal_places_factor1() {
        let r = UnitRepresentationDescription {
            caption: "Hello".to_string(),
            short_caption: "World".to_string(),
            offset: 0f64,
            factor: 1f64,
            measurement_system: MeasurementSystem::Any,
        };
        assert_eq!(r.format(1.234567, 1.0), "1".to_string());
        assert_eq!(r.format(1.234567, 0.1), "1.2".to_string());
        assert_eq!(r.format(1.234567, 0.2), "1.2".to_string());
        assert_eq!(r.format(1.234567, 0.001), "1.235".to_string());
        assert_eq!(r.format(1.234567, 0.0001), "1.2346".to_string());
    }

    #[test]
    fn decimal_places_offset0_factor1000() {
        let r = UnitRepresentationDescription {
            caption: "Hello".to_string(),
            short_caption: "World".to_string(),
            offset: 0f64,
            factor: 1000f64,
            measurement_system: MeasurementSystem::Any,
        };

        // Raw value converted to precision with many decimal places
        assert_eq!(
            format!("{:.*}", 12, r.raw_to_representation(5678.9012)),
            "5.678901200000".to_string()
        );

        assert_eq!(r.format(5678.9012, 1000.0), "6".to_string());
        assert_eq!(r.format(5678.9012, 100.0), "5.7".to_string());
        assert_eq!(r.format(5678.9012, 10.0), "5.68".to_string());
        assert_eq!(r.format(5678.9012, 1.0), "5.679".to_string());
        assert_eq!(r.format(5678.9012, 0.2), "5.6789".to_string());
        assert_eq!(r.format(5678.9012, 0.1), "5.6789".to_string());
        assert_eq!(r.format(5678.9012, 0.01), "5.67890".to_string());
        assert_eq!(r.format(5678.9012, 0.001), "5.678901".to_string());
        // The algorithm may fail for very low resolutions compared to
        // the number of decimal places in the converted value.
        assert_eq!(
            r.format(5678.9012, 0.0001),
            "5.678901200000".to_string()
        );
    }

    #[test]
    fn decimal_places_offset2_factor4() {
        let r = UnitRepresentationDescription {
            caption: "Hello".to_string(),
            short_caption: "World".to_string(),
            offset: 2f64,
            factor: 4f64,
            measurement_system: MeasurementSystem::Any,
        };

        // Raw value converted to precision with many decimal places
        assert_eq!(
            format!("{:.*}", 12, r.raw_to_representation(5.6789012)),
            "0.919725300000".to_string()
        );
        // Precision converted to representation
        assert_eq!(
            format!("{:.*}", 12, r.raw_to_representation_relative(1.0)),
            "0.250000000000".to_string()
        );

        assert_eq!(r.format(5.6789012, 1000.0), "1".to_string());
        assert_eq!(r.format(5.6789012, 100.0), "1".to_string());
        assert_eq!(r.format(5.6789012, 10.0), "0.9".to_string());
        assert_eq!(r.format(5.6789012, 1.0), "0.92".to_string());
        assert_eq!(r.format(5.6789012, 0.2), "0.92".to_string());
        assert_eq!(r.format(5.6789012, 0.1), "0.920".to_string());
        assert_eq!(r.format(5.6789012, 0.01), "0.9197".to_string());
        assert_eq!(r.format(5.6789012, 0.001), "0.91973".to_string());
        assert_eq!(r.format(5.6789012, 0.0001), "0.919725".to_string());
    }
}

pub trait GetByUnitReference {
    fn get_by_reference(
        &self,
        reference: &UnitReference,
    ) -> (
        Option<&UnitDescription>,
        Option<&UnitRepresentationDescription>,
    );
}

impl GetByUnitReference for IndexMap<String, UnitDescription> {
    fn get_by_reference(
        &self,
        reference: &UnitReference,
    ) -> (
        Option<&UnitDescription>,
        Option<&UnitRepresentationDescription>,
    ) {
        let unit = self.get(&reference.unit_id);

        let representation = unit
            .iter()
            .filter_map(|unit| {
                reference
                    .representations
                    .iter()
                    .filter_map(|representation_id| {
                        unit.representations.get(representation_id)
                    })
                    .next()
            })
            .next();

        (unit, representation)
    }
}

#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
#[serde(rename_all = "PascalCase")]
pub enum MeasurementSystem {
    Metric,
    Imperial,
    Any,
}

#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct UnitReference {
    #[serde(with = "idstring")]
    pub unit_id: String,

    // TODO: verify unique items
    // TODO: verify that the items have idstring pattern
    pub representations: Vec<String>,
}

#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct ResultReference {
    #[serde(with = "idstring")]
    pub result_id: String,

    #[serde(with = "idstring")]
    pub representation: String,
}

#[cfg(test)]
mod tests {
    use serde_json::from_str;

    use super::*;

    #[test]
    fn test_device_id() {
        let json = json!({
            "serialNumber": "SN1234",
            "deviceUuid": "e7ab4013-fadd-440b-9072-9dd88b220b59",
        })
        .to_string();

        let deserialized: DeviceId = from_str(&json).unwrap();

        let d = DeviceId {
            serial_number: "SN1234".to_string(),
            device_uuid: Uuid::parse_str(
                "e7ab4013-fadd-440b-9072-9dd88b220b59",
            )
            .unwrap(),
        };

        assert_eq!(d, deserialized);
    }

    #[test]
    #[should_panic]
    #[allow(unused_variables)]
    fn test_device_id_with_invalid_serialnumber() {
        let json = json!({
            "serialNumber": " SN600",
            "deviceUuid": "e7ab4013-fadd-440b-9072-9dd88b220b59",
        })
        .to_string();

        let deserialized: DeviceId = from_str(&json).unwrap();
    }

    #[test]
    #[should_panic]
    #[allow(unused_variables)]
    fn test_device_id_with_invalid_uuid() {
        let json = json!({
            "serialNumber": "SN600",
            "deviceUuid": "abcdefgh",
        })
        .to_string();

        let deserialized: DeviceId = from_str(&json).unwrap();
    }

    #[test]
    fn test_device_description() {
        let json = json!({
            "_caption": "My Super Device",
            "manufacturer": "My Super Company",
            "modelNumber": "SDX1000",
            "revision": "v1.0",
            "iconId": "myIcon",
            "uuid": "2b8fb031-adab-48f4-81ff-479090858909",
        })
        .to_string();

        let deserialized: DeviceDescription = from_str(&json).unwrap();

        let d = DeviceDescription {
            caption: "My Super Device".to_string(),
            manufacturer: "My Super Company".to_owned(),
            model_number: "SDX1000".to_owned(),
            revision: "v1.0".to_owned(),
            icon_id: "myIcon".to_owned(),
            uuid: Uuid::parse_str("2b8fb031-adab-48f4-81ff-479090858909")
                .unwrap(),
        };

        assert_eq!(d, deserialized);
    }

}