rstango 0.3.0

Implementation of the Tango distributed control system
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
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
//! Implementation of attribute instantiations.

use std::time::{Duration, Instant, SystemTime};
use std::sync::{Arc, Mutex};
use std::cmp::Ordering;
use std::borrow::Cow;

use tracing::warn;

use crate::dev::{AttrConfig, AttrDeltaConfig, AttrInfo, AttrMemorized, AttrMode, AttrNumber, AttrQuality, AttrRangeConfig, AttrRead, 
    AttrValueEvent, Named};
use crate::value::{AttrDataKind, DevEnum, Spectrum, Value, ValueFormat};
use crate::error::{reason, Error, ErrorKind, Result};
use crate::buf::Element;

use super::def::{AttrDef, ReadFn, WriteFn};
use super::dev::{Access, Dev, ModelRef};
use super::Model;


/// An attribute of a single device, together with the last value written to it, which
/// Tango keeps aside from the model, and its configuration on that device. Its definition
/// is shared the way that of a [`Command`] is.
pub struct Attr<M: Model> {
    /// Attribute def, behind a pointer because it's a huge structure.
    def: Arc<AttrDef<M>>,
    /// The last value written to that attribute, which every read of it gives back
    /// alongside the read value, so that a client always knows what the device was asked
    /// for as well as what it does.
    /// 
    /// Behind a lock of its own rather than in [`DevMutable`]: it is updated by a write,
    /// which holds the model, and the interface store is the one lock taken *under* the
    /// model, never around it.
    w_value: Mutex<Option<Value>>,
    /// When that attribute was last written, which the delta alarm gives the device time
    /// from to reach the value written, see [`AttrDeltaConfig`]. A set point the device
    /// gives itself, or restores, is not a write and gives it none.
    w_time: Mutex<Option<Instant>>,
    /// The configuration of that attribute on its device, see [`AttrSetup`], behind a lock
    /// of its own for the same reason as the write value.
    setup: Mutex<AttrSetup>,
}

/// How an attribute is configured on its device: the configuration of its definition,
/// which the database overrides once it is asked, see [`Attr::load_config`].
struct AttrSetup {
    /// The inner attribute config that is actually being returned when getting attribute
    /// configuration.
    config: AttrConfig,
    /// What the database holds of the attribute that could not be applied, which every
    /// read and write of it fails with until the device is initialized again: an attribute
    /// whose bounds or units are not the ones it was configured with is one a client must
    /// not trust.
    error: Option<String>,
    /// Whether the database was asked for that configuration.
    loaded: bool,
    /// The memorized value the database holds for an attribute that writes it again, which
    /// is written once the model is built, see [`Attr::restore`].
    restore: Option<Value>,
    /// Why the memorized value could not be restored, which every read fails with until a
    /// write gives the attribute a value again: a client must not take for the set point a
    /// value the device was never given back.
    mem_error: Option<String>,
}

impl<M: Model> Attr<M> {

    /// A new attribute of a device, from its definition, which nothing was written to yet.
    pub(super) fn new(def: Arc<AttrDef<M>>) -> Self {
        
        let setup = AttrSetup { 
            config: def.config.clone(), 
            error: None, 
            loaded: false, 
            restore: None, 
            mem_error: None,
        };

        Self { 
            def, 
            w_value: Mutex::new(None), 
            w_time: Mutex::new(None),
            setup: Mutex::new(setup),
        }

    }

    /// The name of that attribute, as its definition gave it.
    #[inline]
    pub fn name(&self) -> &str {
        &self.def.name
    }

    /// The configuration of that attribute on its device.
    pub fn config(&self) -> AttrConfig {
        self.setup.lock().unwrap().config.clone()
    }

    /// Whether the database was asked for the configuration of that attribute, which is
    /// done for the whole device at once, see [`Dev::init`].
    pub(super) fn is_loaded(&self) -> bool {
        self.setup.lock().unwrap().loaded
    }

    /// Whether that attribute has any alarm configured: a bound of its alarm or warning
    /// range, or a delta, which is what a device in alarm looks at, see
    /// [`Dev::set_auto_alarm_states`].
    pub(super) fn has_alarms(&self) -> bool {
        let config = &self.setup.lock().unwrap().config;
        config.alarm.is_set() || config.warning.is_set() || config.delta.is_some()
    }

    /// Configure that attribute from what the database holds of it: the properties it holds
    /// for the attribute at the level of the class and then of the device, the device
    /// overriding the class, and both the definition.
    /// 
    /// A level the database could not be asked for, and a property that cannot be applied,
    /// leave what came before them in place and are kept as the error of the attribute, see
    /// [`AttrSetup::error`].
    /// 
    /// The memorized value of the attribute, which only the device holds, is taken here
    /// too the first time: it is the set point right away for an attribute that only
    /// restores it, and is kept to be written for one that writes it again, see
    /// [`Self::restore`]. Configuring it again, once a client changed its configuration,
    /// leaves its set point alone.
    pub(super) fn load_config(&self, dev: &Dev<M>, class: PropsResult<'_>, device: PropsResult<'_>) {

        let mut loader = ConfigLoader::new(&self.def.config, self.def.kind);
        loader.apply_level("class", class);
        loader.apply_level("device", device);

        let (config, mut error) = loader.finish();
        if let Some(incoherence) = incoherence(&config) {
            error = Some(match error {
                Some(error) => format!("{error}, {incoherence}"),
                None => incoherence,
            });
        }

        if let Some(error) = &error {
            warn!(dev = %dev.name(), attr = %self.name(), err = %error, "Failed to configure the attribute from the database");
        }

        let mut setup = self.setup.lock().unwrap();
        if setup.loaded {
            setup.config = config;
            setup.error = error;
            return;
        }

        let mut restore = None;
        let mut mem_error = None;

        // Check if the device attribute properties have a __value property...
        let mem_value = device.ok()
            .and_then(|props| props
                .iter()
                .find(|prop| prop.name.value().eq_ignore_ascii_case(MEM_VALUE)));

        if let (Some(mode), Some(mem_value)) = (self.def.memorized, mem_value) {
            match parse_mem_value(self.def.kind.as_ref(), &mem_value.value) {
                Ok(None) => {}
                Ok(Some(value)) => match mode {
                    AttrMemorized::RestoreSetPoint => *self.w_value.lock().unwrap() = Some(value),
                    AttrMemorized::RestoreAndWrite => restore = Some(value),
                }
                Err(err) => {
                    warn!(dev = %dev.name(), attr = %self.name(), %err, "Failed to parse the memorized value");
                    mem_error = Some(format!("the memorized value cannot be parsed: {err}"));
                }
            }
        }

        *setup = AttrSetup { 
            config, 
            error, 
            loaded: true, 
            restore, 
            mem_error,
        };

    }

    /// Change the configuration of that attribute to the requested one, given what the
    /// database holds for its class, giving back what that does to what the database holds
    /// for it on its device.
    /// 
    /// The requested configuration is the whole configuration the attribute is to have, which
    /// a client gets by reading the one it has and changing what it means to, so every field
    /// is one of:
    /// 
    /// - what the attribute has already, which is left alone;
    /// - a value, stored for the device, unless it is what the device inherits, in which case
    ///   the device has nothing of its own to store and it is deleted;
    /// - no value, which brings the field back to what the device inherits, deleting what it
    ///   has of its own.
    /// 
    /// No value therefore never means *no value* when the device inherits one, which is the
    /// one thing cppTango does that this does not: forcing the library default over the
    /// defaults of the class.
    /// 
    /// The requested configuration is refused, nothing being changed, if it gives a value
    /// to a property the kind of the attribute does not support, see
    /// [`ConfigProp::supported_by`]. The configuration the attribute ends up with is refused
    /// too if it is incoherent, see [`incoherence`], or if it leaves out the set point of a memorized
    /// attribute, which its next initialization would then fail to restore. Once changed, the
    /// error of the attribute is what could not be applied of its class, see
    /// [`AttrSetup::error`].
    pub(super) fn change_config(&self, class: &[Named<Spectrum<str>>], requested: &AttrConfig) -> std::result::Result<ConfigChanges, String> {

        // What the device inherits, the definition which the class overrides, which is what
        // the configuration it ends up with starts from: every field is the inherited one
        // unless the device has one of its own.
        let mut config = ConfigLoader::new(&self.def.config, self.def.kind);
        config.apply_level("class", Ok(class));
        let (mut config, class_error) = config.finish();

        if let Some(prop) = unsupported_prop(requested, self.def.kind) {
            return Err(format!("its property {:?} is {}", prop.name(), unsupported(self.def.kind)));
        }

        let w_value = self.def.memorized.and_then(|_| self.w_value.lock().unwrap().clone());

        let mut setup = self.setup.lock().unwrap();
        let mut changes = ConfigChanges::default();

        for prop in ConfigProp::ALL {

            let target = prop_value(requested, prop);
            let now = prop_value(&setup.config, prop);
            let inherited = prop_value(&config, prop);

            if target.is_unset() || target == inherited {
                // The device has something of its own only if what it has is not inherited.
                if now != inherited {
                    changes.del.push(prop);
                }
            } else {
                if target != now {
                    changes.put.push((prop, target.to_values()));
                }
                copy_prop(&mut config, requested, prop);
            }

        }

        if let Some(incoherence) = incoherence(&config) {
            return Err(incoherence);
        }

        if let Some(w_value) = &w_value {
            if any_number(w_value, |number| outside(&config.range, number)) {
                return Err("its memorized value would be outside of its range".to_string());
            }
        }

        // The configuration is the requested one over the inherited one, so what could not
        // be applied of the class is all that is left wrong with it.
        setup.config = config;
        setup.error = class_error;
        Ok(changes)

    }

    /// Write the memorized value the database held for that attribute, if it writes it
    /// again and its device has just been initialized into that model, see
    /// [`AttrMemorized::RestoreAndWrite`]. The value is written as a client would write
    /// it, but is not stored again, being the one the database already holds.
    /// 
    /// An attribute whose configuration could not be applied is not written: its bounds
    /// are not the ones it was configured with.
    pub(super) async fn restore(&self, dev: &Dev<M>, model: &mut M) {

        let Some(value) = self.setup.lock().unwrap().restore.take() else {
            return;
        };

        if self.check_config(dev, false).is_err() {
            return;
        }

        if let Err(err) = self.write_inner(dev, &mut ModelRef::Exclusive(model), value).await {
            warn!(dev = %dev.name(), attr = %self.name(), %err, "Failed to write the memorized value back");
            self.setup.lock().unwrap().mem_error = Some(format!("the memorized value cannot be \
                written back: {}", err.description()));
        }

    }

    /// Fail if the configuration of that attribute could not be applied, see
    /// [`AttrSetup::error`], and, when asked to, if its memorized value could not be
    /// restored, see [`AttrSetup::mem_error`], which only fails a read: a write is what
    /// gives the attribute a set point again.
    fn check_config(&self, dev: &Dev<M>, check_mem: bool) -> Result<()> {
        
        let setup = self.setup.lock().unwrap();
        
        if let Some(error) = &setup.error {
            return Err(Error::new(ErrorKind::Reason(reason::API_AttrConfig))
                .with_description(format!("The attribute {:?} of the device {:?} has a wrong \
                    configuration in the database: {error}", self.name(), dev.name())));
        }

        if check_mem && let Some(error) = &setup.mem_error {
            return Err(Error::new(ErrorKind::Reason(reason::API_MemAttFailedDuringInit))
                .with_description(format!("The attribute {:?} of the device {:?} has no set \
                    point, {error}, it has to be written again", self.name(), dev.name())));
        }

        Ok(())

    }

    /// Whether that attribute is memorized, see [`AttrMemorized`].
    #[inline]
    pub fn is_memorized(&self) -> bool {
        self.def.memorized.is_some()
    }

    /// Give that attribute a new set point without writing it: the write function is not
    /// called, and the value is what every read gives back as the write value from then
    /// on, and what the database remembers of a memorized attribute.
    /// 
    /// This is for a device whose set point changes by itself, a motor stopped short of its
    /// target for instance, so that a client and the next initialization find the value
    /// the device actually works towards.
    pub(super) async fn set_w_value(&self, dev: &Dev<M>, value: Value) -> Result<()> {
        *self.w_value.lock().unwrap() = Some(value.clone());
        self.setup.lock().unwrap().mem_error = None;
        self.store(dev, &value).await
    }

    /// Store that value as the memorized value of that attribute, if it is memorized.
    async fn store(&self, dev: &Dev<M>, value: &Value) -> Result<()> {
        if self.def.memorized.is_none() {
            return Ok(());
        }
        let mem_value = mem_value_str(value)
            .map_err(|err| Error::new(ErrorKind::Reason(reason::API_AttrConfig))
                .with_description(format!("The attribute {:?} of the device {:?} cannot be \
                    memorized: {err}", self.name(), dev.name())))?;
        dev.server().database()
            .set_dev_attr_prop_async(dev.name(), (self.name(), (MEM_VALUE, mem_value)))
            .await
    }

    /// The access reading that attribute needs to the model.
    pub(super) fn read_access(&self) -> Access {
        match &self.def.read {
            Some(ReadFn::ExclusiveSync(_) | ReadFn::ExclusiveAsync(_)) => Access::Exclusive,
            _ => Access::Shared,
        }
    }

    /// The access writing that attribute needs to the model.
    pub(super) fn write_access(&self) -> Access {
        match &self.def.write {
            Some(WriteFn::ExclusiveSync(_) | WriteFn::ExclusiveAsync(_)) => Access::Exclusive,
            _ => Access::Shared,
        }
    }

    /// Whether reading that attribute may block, its read function being synchronous, see
    /// [`crate::pool::run`].
    pub(super) fn read_may_block(&self) -> bool {
        matches!(&self.def.read, Some(ReadFn::SharedSync(_) | ReadFn::ExclusiveSync(_)))
    }

    /// Whether writing that attribute may block, see [`Self::read_may_block`].
    pub(super) fn write_may_block(&self) -> bool {
        matches!(&self.def.write, Some(WriteFn::SharedSync(_) | WriteFn::ExclusiveSync(_)))
    }

    /// What a client is told of that attribute: what it may read and change of its
    /// configuration, and what its definition advertises of its data.
    /// 
    /// A definition advertising neither a kind nor a format, which only one built out of a
    /// raw handler and given neither can be, has nothing to tell a client of its data and
    /// is answered with an error rather than with a guess.
    /// 
    /// An attribute whose configuration could not be applied is described all the same,
    /// with what could be, so that a client can still see what it is configured with.
    /// 
    /// TODO: [`AttrMode::ReadWithWrite`] cannot be derived from the handlers, the write
    /// attribute it is paired with having to be named; it needs its own definition.
    pub fn info(&self) -> Result<AttrInfo> {
        self.info_as(match (&self.def.read, &self.def.write) {
            (Some(_), Some(_)) => AttrMode::ReadWrite,
            (Some(_), None) => AttrMode::Read,
            (None, Some(_)) => AttrMode::Write,
            // An attribute that has no handler yet is advertised as anything a handler
            // could make it, every read and write of it failing, see [`Self::no_handler_err`].
            (None, None) => AttrMode::ReadWrite,
        })
    }

    /// The error of reading or writing that attribute when it has no handler at all, see
    /// [`Self::info`].
    fn no_handler_err(&self, dev: &Dev<M>) -> Error {
        Error::not_implemented()
            .with_description(format!("The attribute {} of the device {} has no handler defined",
                self.name(), dev.name()))
    }

    /// Refuse a subscription to the events of that kind of that attribute if nothing ever
    /// sends them, and a push of one the device did not declare: the change and archive events are only sent once the device declares it
    /// pushes them, see [`AttrDef::push_change_event`], and the periodic ones never with no
    /// polling. The user and alarm events, which only a device pushes, are always allowed,
    /// as cppTango allows them.
    pub(super) fn check_push_event(&self, dev: &Dev<M>, event: AttrValueEvent) -> Result<()> {

        let pushed = match event {
            AttrValueEvent::Change => self.def.pushed.change.is_some(),
            AttrValueEvent::Archive => self.def.pushed.archive.is_some(),
            AttrValueEvent::Periodic => false,
            AttrValueEvent::User | 
            AttrValueEvent::Alarm => true,
        };

        if pushed {
            return Ok(());
        }

        Err(Error::new(ErrorKind::Reason(reason::API_AttributePollingNotStarted))
            .with_description(format!("The polling (necessary to send events) for the attribute {} \
                of the device {} is not started, and the device does not push its {event:?} events",
                self.name(), 
                dev.name())))

    }

    /// What a client is told of that attribute, accessed in that mode whatever its
    /// handlers, which is how the State and the Status are described: they are read
    /// through the device rather than through a handler of their own, see [`Self::info`].
    pub(super) fn info_as(&self, mode: AttrMode) -> Result<AttrInfo> {
        Ok(AttrInfo {
            config: self.config(),
            mode,
            data_kind: self.def.kind
                .ok_or_else(|| Error::new(ErrorKind::Internal)
                    .with_description(format!("The attribute {} does not advertise the kind \
                        of its data", self.name())))?,
            data_format: self.def.format
                .ok_or_else(|| Error::new(ErrorKind::Internal)
                    .with_description(format!("The attribute {} does not advertise the \
                        format of its data", self.name())))?,
            display_level: self.def.display_level,
            memorized: self.def.memorized,
        })
    }

    /// The alarm that reading is in: the one the read function gave it, or else the one
    /// the configuration of that attribute puts it in, outside of the alarm range, outside
    /// of the warning range, or too far from the value written for longer than the device
    /// is given to reach it, see [`AttrDeltaConfig`].
    /// 
    /// A quality the read function gave is never overridden, the device always having the
    /// last word on the quality of its own readings, and it counts the way cppTango counts
    /// it: an ALARM or a WARNING it gave is an alarm all the same.
    fn alarm(&self, read: &AttrRead<Value>) -> Option<AttrAlarm> {

        let value = match (read.quality, &read.value) {
            (AttrQuality::Alarm | AttrQuality::Warning, _) => return Some(AttrAlarm::Device(read.quality)),
            (AttrQuality::Valid, Some(value)) => value,
            _ => return None,
        };

        let (alarm, warning, delta) = {
            let config = &self.setup.lock().unwrap().config;
            (config.alarm, config.warning, config.delta)
        };

        if any_number(value, |number| outside(&alarm, number)) {
            return Some(AttrAlarm::Alarm);
        }

        if any_number(value, |number| outside(&warning, number)) {
            return Some(AttrAlarm::Warning);
        }

        if let (Some(delta), Some(w_value)) = (delta, &read.w_value) {
            let written = *self.w_time.lock().unwrap();
            let settled = written.is_some_and(|time| time.elapsed() >= delta.time.unwrap_or_default());
            if settled && drifted(value, w_value, delta.value) {
                return Some(AttrAlarm::Delta);
            }
        }

        None

    }

    /// Read that attribute, see [`Self::read`], giving back along with the reading the
    /// alarm its configuration puts it in, if any, see [`Self::alarm`].
    pub(super) async fn read_with_alarm(&self, dev: &Dev<M>, model: &mut ModelRef<'_, M>) -> Result<(AttrRead<Value>, Option<AttrAlarm>)> {
        let mut read = self.read_inner(dev, model).await?;
        let alarm = self.alarm(&read);
        if let Some(alarm) = alarm {
            read.quality = alarm.quality();
        }
        Ok((read, alarm))
    }

    /// Read that attribute on the model, borrowed with the access [`Self::read_access`]
    /// asked for, its quality being the one its configuration gives it, see
    /// [`Self::alarm`].
    pub(super) async fn read(&self, dev: &Dev<M>, model: &mut ModelRef<'_, M>) -> Result<AttrRead<Value>> {
        self.read_with_alarm(dev, model).await.map(|(read, _)| read)
    }

    /// Read that attribute as its device gives it, see [`Self::read`].
    async fn read_inner(&self, dev: &Dev<M>, model: &mut ModelRef<'_, M>) -> Result<AttrRead<Value>> {

        self.check_config(dev, true)?;

        let mut read = match &self.def.read {
            Some(ReadFn::SharedSync(func)) => func(model.shared(), dev)?,
            Some(ReadFn::ExclusiveSync(func)) => func(model.exclusive()?, dev)?,
            Some(ReadFn::SharedAsync(func)) => func(model.shared(), dev).await?,
            Some(ReadFn::ExclusiveAsync(func)) => func(model.exclusive()?, dev).await?,
            None if self.def.write.is_none() => return Err(self.no_handler_err(dev)),
            // A write-only attribute has nothing to read but what was written to it, which
            // is what Tango gives for one: the set point back, and no read value, rather
            // than an error.
            None => AttrRead {
                value: None,
                w_value: None,
                quality: AttrQuality::Valid,
                time: SystemTime::now(),
            },
        };

        self.merge_w_value(&mut read);
        Ok(read)

    }

    /// Give a reading that has no write value the last one that was written, and keep the
    /// write value of one that has it, so that the readings that follow give that one back.
    /// Either way what a client gets, read or pushed, does not depend on the model having
    /// kept the value it was written.
    pub(super) fn merge_w_value(&self, read: &mut AttrRead<Value>) {
        match &read.w_value {
            None => read.w_value = self.w_value.lock().unwrap().clone(),
            Some(w_value) => *self.w_value.lock().unwrap() = Some(w_value.clone()),
        }
    }

    /// Write that attribute on the model, borrowed with the access [`Self::write_access`]
    /// asked for, keep the value that was written and store it if the attribute is
    /// memorized.
    /// 
    /// A value the device accepted but the database could not store fails the write all
    /// the same, the way cppTango does: it is the set point of the device, but not the one
    /// its next initialization finds.
    pub(super) async fn write(&self, dev: &Dev<M>, model: &mut ModelRef<'_, M>, value: Value) -> Result<()> {
        self.check_config(dev, false)?;
        self.write_inner(dev, model, value.clone()).await?;
        self.store(dev, &value).await
    }

    /// Write that attribute on the model and keep the value that was written, see
    /// [`Self::write`].
    async fn write_inner(&self, dev: &Dev<M>, model: &mut ModelRef<'_, M>, value: Value) -> Result<()> {

        self.check_limits(dev, &value)?;

        // The handler and the server share the written value, the server keeping it for
        // the reads.
        match &self.def.write {
            Some(WriteFn::SharedSync(func)) => func(model.shared(), dev, value.clone())?,
            Some(WriteFn::ExclusiveSync(func)) => func(model.exclusive()?, dev, value.clone())?,
            Some(WriteFn::SharedAsync(func)) => func(model.shared(), dev, value.clone()).await?,
            Some(WriteFn::ExclusiveAsync(func)) => func(model.exclusive()?, dev, value.clone()).await?,
            None if self.def.read.is_none() => return Err(self.no_handler_err(dev)),
            None => return Err(Error::new(ErrorKind::AttrNotWritable)
                .with_append_description(format_args!("Attribute {:?} of the device {:?}",
                    self.name(), dev.name()))),
        }

        // Only a write the device accepted is remembered: a write value a client reads
        // back is one the device is actually working towards, which also gives back a set
        // point to an attribute whose memorized value could not be restored.
        *self.w_value.lock().unwrap() = Some(value);
        *self.w_time.lock().unwrap() = Some(Instant::now());
        self.setup.lock().unwrap().mem_error = None;
        Ok(())

    }

    /// Fail if a number of that value is outside the range of values of that attribute,
    /// which is the range a value written to it has to be in, see [`AttrConfig::range`].
    /// A value that is not a number has no range to be outside of.
    fn check_limits(&self, dev: &Dev<M>, value: &Value) -> Result<()> {

        let range = self.setup.lock().unwrap().config.range;
        if !any_number(value, |number| outside(&range, number)) {
            return Ok(());
        }

        let bound = |bound: Option<AttrNumber>| bound.map_or_else(|| "-".to_string(), |bound| bound.to_string());
        Err(Error::new(ErrorKind::Reason(reason::API_WAttrOutsideLimit))
            .with_description(format!("The value written to the attribute {:?} of the device {:?} is \
                outside of its range [{}, {}]", self.name(), dev.name(), bound(range.min), bound(range.max))))
        
    }

}

/// The alarm the configuration of an attribute puts a reading of it in, see
/// [`Attr::alarm`].
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum AttrAlarm {
    /// Outside of the alarm range.
    Alarm,
    /// Outside of the warning range.
    Warning,
    /// Too far from the value written.
    Delta,
    /// In that quality, which the read function gave it.
    Device(AttrQuality),
}

impl AttrAlarm {

    /// The quality of a reading in that alarm.
    pub fn quality(self) -> AttrQuality {
        match self {
            Self::Alarm | Self::Delta => AttrQuality::Alarm,
            Self::Warning => AttrQuality::Warning,
            Self::Device(quality) => quality,
        }
    }

    /// Why an attribute of that name is in that alarm, as the status of its device says.
    pub fn describe(self, name: &str) -> String {
        match self {
            Self::Alarm => format!("Alarm: the attribute {name} is outside of its alarm range"),
            Self::Warning => format!("Warning: the attribute {name} is outside of its warning range"),
            Self::Delta => format!("Alarm: the attribute {name} is too far from the value written to it"),
            Self::Device(AttrQuality::Warning) => format!("Warning: the attribute {name} is in WARNING"),
            Self::Device(_) => format!("Alarm: the attribute {name} is in ALARM"),
        }
    }

}

// =========================== //
//           Limits            //
// =========================== //

/// Whether that predicate holds for any number of that value, a value of a kind that is
/// not a number having none: every element of an array is one of its numbers.
fn any_number(value: &Value, mut pred: impl FnMut(AttrNumber) -> bool) -> bool {

    macro_rules! any {
        ($format:expr) => {
            match $format {
                ValueFormat::Scalar(data) => data.iter().any(|number| pred(number.into())),
                ValueFormat::Spectrum(data) => data.iter().any(|number| pred(number.into())),
                ValueFormat::Image(data) => data.iter().any(|number| pred(number.into())),
            }
        };
    }

    match value {
        Value::Octet(format) => any!(format),
        Value::UShort(format) => any!(format),
        Value::Short(format) => any!(format),
        Value::ULong(format) => any!(format),
        Value::Long(format) => any!(format),
        Value::ULong64(format) => any!(format),
        Value::Long64(format) => any!(format),
        Value::Float(format) => any!(format),
        Value::Double(format) => any!(format),
        _ => false,
    }

}

/// Whether that number is outside of that range, both bounds being part of it, a number
/// that cannot be compared with a bound, a not-a-number, being outside of any.
fn outside(range: &AttrRangeConfig, number: AttrNumber) -> bool {
    let below = range.min.is_some_and(|min| number.partial_cmp(&min).is_none_or(Ordering::is_lt));
    let above = range.max.is_some_and(|max| number.partial_cmp(&max).is_none_or(Ordering::is_gt));
    below || above
}

/// Whether a number of the read value is further than that from the number of the value
/// written at the same place, the two being compared element by element.
fn drifted(read: &Value, written: &Value, delta: AttrNumber) -> bool {

    let mut written_numbers = Vec::new();
    any_number(written, |number| {
        written_numbers.push(number.as_f64());
        false
    });
    
    let delta = delta.as_f64();
    let mut written_numbers = written_numbers.into_iter();
    any_number(read, |number| written_numbers.next()
        .is_some_and(|written| (number.as_f64() - written).abs() > delta))
    
}

// =========================== //
//   Database configuration    //
// =========================== //

/// What the database holds for an attribute at one level, or why it could not be asked.
pub type PropsResult<'a> = std::result::Result<&'a [Named<Spectrum<str>>], &'a Error>;

// The strings standing for a property that has no value, which bring the field back to no
// value at all whatever the levels below gave it, see `NOT_SPECIFIED` in the CORBA module.
const NOT_SPECIFIED: &str = "Not specified";
const NOT_A_NUMBER: &str = "NaN";

/// The configuration of an attribute being built out of the properties the database holds
/// for it, starting from the one of its definition.
struct ConfigLoader {
    config: AttrConfig,
    /// The data kind of that attribute, which its limits are read as, and which some
    /// properties are not supported by, see [`ConfigProp::supported_by`].
    kind: Option<AttrDataKind>,
    /// The two halves of the delta alarm, which are two properties that each level may give
    /// one of, and which only make an alarm together, see [`Self::finish`].
    delta_value: Option<AttrNumber>,
    delta_time: Option<Duration>,
    /// Every property that could not be applied, described.
    errors: Vec<String>,
}

impl ConfigLoader {

    fn new(config: &AttrConfig, kind: Option<AttrDataKind>) -> Self {
        Self {
            config: config.clone(),
            kind,
            delta_value: config.delta.map(|delta| delta.value),
            delta_time: config.delta.and_then(|delta| delta.time),
            errors: Vec::new(),
        }
    }

    /// Apply every property the database holds at that level, named after it in the errors.
    fn apply_level(&mut self, level: &str, props: PropsResult<'_>) {
        match props {
            Ok(props) => {
                for prop in props {
                    if let Err(err) = self.apply(prop.name.value(), &prop.value) {
                        self.errors.push(format!("{level} property {:?}: {err}", prop.name.value()));
                    }
                }
            }
            Err(err) => self.errors.push(format!("{level} properties: {}", err.description())),
        }
    }

    /// Apply the property of that name. A property that is not one of the configuration is
    /// left alone: the database holds more of an attribute than its configuration, the
    /// value of a memorized one for instance.
    fn apply(&mut self, name: &str, values: &Spectrum<str>) -> std::result::Result<(), String> {
        match ConfigProp::from_name(name) {
            Some(prop) => self.apply_prop(prop, values),
            None => Ok(()),
        }
    }

    /// Apply that property, see [`Self::apply`]. A property the kind of the attribute does
    /// not support is refused unless it has no value.
    fn apply_prop(&mut self, prop: ConfigProp, values: &Spectrum<str>) -> std::result::Result<(), String> {

        if !prop.supported_by(self.kind) {
            return match values.iter().all(|value| is_unset(value.trim())) {
                true => Ok(()),
                false => Err(unsupported(self.kind)),
            };
        }
        
        let config = &mut self.config;
        let limits = limit_kind(self.kind);
        
        match prop {
            ConfigProp::Description => config.doc = text(values),
            ConfigProp::Label => config.label = text(values),
            ConfigProp::Unit => config.unit = text(values),
            ConfigProp::StandardUnit => config.standard_unit = number(values)?,
            ConfigProp::DisplayUnit => config.display_unit = text(values),
            ConfigProp::Format => config.display_format = text(values),
            ConfigProp::MinValue => config.range.min = limit(values, limits)?,
            ConfigProp::MaxValue => config.range.max = limit(values, limits)?,
            ConfigProp::MinAlarm => config.alarm.min = limit(values, limits)?,
            ConfigProp::MaxAlarm => config.alarm.max = limit(values, limits)?,
            ConfigProp::MinWarning => config.warning.min = limit(values, limits)?,
            ConfigProp::MaxWarning => config.warning.max = limit(values, limits)?,
            ConfigProp::DeltaVal => self.delta_value = limit(values, limits)?,
            // A delta time of zero is how cppTango says there is none.
            ConfigProp::DeltaT => self.delta_time = duration(values)?.filter(|time| !time.is_zero()),
            ConfigProp::RelChange => config.change_event.rel_change = change(values)?,
            ConfigProp::AbsChange => config.change_event.abs_change = change(values)?,
            ConfigProp::EventPeriod => config.periodic_event.period = duration(values)?,
            ConfigProp::ArchiveRelChange => config.archive_event.rel_change = change(values)?,
            ConfigProp::ArchiveAbsChange => config.archive_event.abs_change = change(values)?,
            ConfigProp::ArchivePeriod => config.archive_event.period = duration(values)?,
            ConfigProp::EnumLabels => config.enum_labels = labels(values),
        }

        Ok(())

    }

    /// The configuration that was built, and the error of what could not be applied.
    fn finish(self) -> (AttrConfig, Option<String>) {
        let mut config = self.config;
        config.delta = self.delta_value.map(|value| AttrDeltaConfig { value, time: self.delta_time });
        let error = (!self.errors.is_empty()).then(|| self.errors.join(", "));
        (config, error)
    }

}

/// The value of one property of a configuration, borrowed from it, which is what two
/// configurations are compared by, property by property, with nothing written out: two
/// values that parse the same are the same value, however they were written.
#[derive(Debug, Clone, Copy, PartialEq)]
enum ConfigPropValue<'a> {
    Text(Option<&'a str>),
    Number(Option<f64>),
    Limit(Option<AttrNumber>),
    Duration(Option<Duration>),
    Labels(&'a [Cow<'static, str>]),
}

impl ConfigPropValue<'_> {

    /// Whether that property has no value.
    fn is_unset(self) -> bool {
        match self {
            Self::Text(text) => text.is_none(),
            Self::Number(number) => number.is_none(),
            Self::Limit(limit) => limit.is_none(),
            Self::Duration(duration) => duration.is_none(),
            Self::Labels(labels) => labels.is_empty(),
        }
    }

    /// The values that property is stored as, a property with no value being stored as
    /// [`NOT_SPECIFIED`], a text being one value per line and a duration a number of
    /// milliseconds.
    fn to_values(self) -> Vec<String> {
        if self.is_unset() {
            return vec![NOT_SPECIFIED.to_string()];
        }
        match self {
            Self::Text(text) => text.unwrap_or_default().split('\n').map(str::to_string).collect(),
            Self::Number(number) => number.iter().map(f64::to_string).collect(),
            Self::Limit(limit) => limit.iter().map(AttrNumber::to_string).collect(),
            Self::Duration(duration) => duration.iter().map(|duration| (duration.as_secs_f64() * 1000.0).to_string()).collect(),
            Self::Labels(labels) => labels.iter().map(|label| label.to_string()).collect(),
        }
    }

}

/// The value of that property of that configuration, see [`ConfigPropValue`].
fn prop_value(config: &AttrConfig, prop: ConfigProp) -> ConfigPropValue<'_> {
    match prop {
        ConfigProp::Description => ConfigPropValue::Text(config.doc.as_deref()),
        ConfigProp::Label => ConfigPropValue::Text(config.label.as_deref()),
        ConfigProp::Unit => ConfigPropValue::Text(config.unit.as_deref()),
        ConfigProp::StandardUnit => ConfigPropValue::Number(config.standard_unit),
        ConfigProp::DisplayUnit => ConfigPropValue::Text(config.display_unit.as_deref()),
        ConfigProp::Format => ConfigPropValue::Text(config.display_format.as_deref()),
        ConfigProp::MinValue => ConfigPropValue::Limit(config.range.min),
        ConfigProp::MaxValue => ConfigPropValue::Limit(config.range.max),
        ConfigProp::MinAlarm => ConfigPropValue::Limit(config.alarm.min),
        ConfigProp::MaxAlarm => ConfigPropValue::Limit(config.alarm.max),
        ConfigProp::MinWarning => ConfigPropValue::Limit(config.warning.min),
        ConfigProp::MaxWarning => ConfigPropValue::Limit(config.warning.max),
        ConfigProp::DeltaVal => ConfigPropValue::Limit(config.delta.map(|delta| delta.value)),
        ConfigProp::DeltaT => ConfigPropValue::Duration(config.delta.and_then(|delta| delta.time)),
        ConfigProp::RelChange => ConfigPropValue::Number(config.change_event.rel_change),
        ConfigProp::AbsChange => ConfigPropValue::Number(config.change_event.abs_change),
        ConfigProp::EventPeriod => ConfigPropValue::Duration(config.periodic_event.period),
        ConfigProp::ArchiveRelChange => ConfigPropValue::Number(config.archive_event.rel_change),
        ConfigProp::ArchiveAbsChange => ConfigPropValue::Number(config.archive_event.abs_change),
        ConfigProp::ArchivePeriod => ConfigPropValue::Duration(config.archive_event.period),
        ConfigProp::EnumLabels => ConfigPropValue::Labels(&config.enum_labels),
    }
}

/// The attribute properties of the database that are part of the configuration of an
/// attribute, see [`ConfigLoader::apply`].
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ConfigProp {
    Description,
    Label,
    Unit,
    StandardUnit,
    DisplayUnit,
    Format,
    MinValue,
    MaxValue,
    MinAlarm,
    MaxAlarm,
    MinWarning,
    MaxWarning,
    DeltaVal,
    DeltaT,
    RelChange,
    AbsChange,
    EventPeriod,
    ArchiveRelChange,
    ArchiveAbsChange,
    ArchivePeriod,
    EnumLabels,
}

impl ConfigProp {

    /// Every property.
    const ALL: [Self; 21] = [
        Self::Description,
        Self::Label,
        Self::Unit,
        Self::StandardUnit,
        Self::DisplayUnit,
        Self::Format,
        Self::MinValue,
        Self::MaxValue,
        Self::MinAlarm,
        Self::MaxAlarm,
        Self::MinWarning,
        Self::MaxWarning,
        Self::DeltaVal,
        Self::DeltaT,
        Self::RelChange,
        Self::AbsChange,
        Self::EventPeriod,
        Self::ArchiveRelChange,
        Self::ArchiveAbsChange,
        Self::ArchivePeriod,
        Self::EnumLabels,
    ];

    /// The name the database holds that property under.
    pub fn name(self) -> &'static str {
        match self {
            Self::Description => "description",
            Self::Label => "label",
            Self::Unit => "unit",
            Self::StandardUnit => "standard_unit",
            Self::DisplayUnit => "display_unit",
            Self::Format => "format",
            Self::MinValue => "min_value",
            Self::MaxValue => "max_value",
            Self::MinAlarm => "min_alarm",
            Self::MaxAlarm => "max_alarm",
            Self::MinWarning => "min_warning",
            Self::MaxWarning => "max_warning",
            Self::DeltaVal => "delta_val",
            Self::DeltaT => "delta_t",
            Self::RelChange => "rel_change",
            Self::AbsChange => "abs_change",
            Self::EventPeriod => "event_period",
            Self::ArchiveRelChange => "archive_rel_change",
            Self::ArchiveAbsChange => "archive_abs_change",
            Self::ArchivePeriod => "archive_period",
            Self::EnumLabels => "enum_labels",
        }
    }

    /// Whether an attribute of that kind supports that property: the bounds, the delta and
    /// the change criteria are values of the attribute, which only a number has, and an
    /// enumerated attribute has no alarm, the way cppTango refuses them.
    fn supported_by(self, kind: Option<AttrDataKind>) -> bool {
        let numeric = !matches!(kind, None | Some(AttrDataKind::Bool | AttrDataKind::State | AttrDataKind::String | AttrDataKind::Encoded));
        match self {
            Self::MinAlarm | 
            Self::MaxAlarm | 
            Self::MinWarning | 
            Self::MaxWarning => numeric && kind != Some(AttrDataKind::Enum),
            Self::MinValue | 
            Self::MaxValue | 
            Self::DeltaVal | 
            Self::DeltaT | 
            Self::RelChange | 
            Self::AbsChange |
            Self::ArchiveRelChange | 
            Self::ArchiveAbsChange => numeric,
            _ => true,
        }
    }

    /// The property of that name, matched ignoring the case like any name the database
    /// holds, absent for one that is not part of the configuration.
    fn from_name(name: &str) -> Option<Self> {
        Self::ALL.into_iter().find(|prop| name.eq_ignore_ascii_case(prop.name()))
    }

}

/// Whether that value of a property stands for no value at all.
fn is_unset(value: &str) -> bool {
    value.is_empty() || value.eq_ignore_ascii_case(NOT_SPECIFIED) || value.eq_ignore_ascii_case(NOT_A_NUMBER)
}

/// A property that is a text, every line of which is one of its values.
fn text(values: &Spectrum<str>) -> Option<Cow<'static, str>> {
    let text = values.iter().collect::<Vec<_>>().join("\n");
    (!is_unset(text.trim())).then_some(Cow::Owned(text))
}

/// The value of a property that has a single one, absent for one that has none.
fn single(values: &Spectrum<str>) -> std::result::Result<Option<&str>, String> {
    let mut iter = values.iter().map(str::trim);
    match (iter.next(), iter.next()) {
        (None, _) => Ok(None),
        (Some(value), None) => Ok((!is_unset(value)).then_some(value)),
        (Some(_), Some(_)) => Err(format!("expected a single value, got {}", values.len())),
    }
}

/// Parse that value as a finite number.
fn parse_number(value: &str) -> std::result::Result<f64, String> {
    value.parse::<f64>().ok()
        .filter(|value| value.is_finite())
        .ok_or_else(|| format!("{value:?} is not a number"))
}

/// A property that is a number.
fn number(values: &Spectrum<str>) -> std::result::Result<Option<f64>, String> {
    single(values)?.map(parse_number).transpose()
}

/// A property that is a limit, which is a value of the attribute and is read as its type,
/// a value that type cannot hold being read as a double, see [`AttrNumber`].
fn limit(values: &Spectrum<str>, kind: LimitKind) -> std::result::Result<Option<AttrNumber>, String> {
    
    let Some(value) = single(values)? else {
        return Ok(None);
    };
    
    let typed = match kind {
        LimitKind::Long => value.parse::<i64>().ok().map(AttrNumber::Long),
        LimitKind::ULong => value.parse::<u64>().ok().map(AttrNumber::ULong),
        LimitKind::Double => None,
    };

    match typed {
        Some(typed) => Ok(Some(typed)),
        None => parse_number(value).map(|value| Some(AttrNumber::Double(value))),
    }

}

/// A property that is a duration, which the database holds in milliseconds.
fn duration(values: &Spectrum<str>) -> std::result::Result<Option<Duration>, String> {

    let Some(millis) = number(values)? else {
        return Ok(None);
    };

    Duration::try_from_secs_f64(millis / 1000.0)
        .map(Some)
        .map_err(|_| format!("{millis} is not a duration in milliseconds"))
    
}

/// A property that is the criterion of an event, which Tango allows to be two values, the
/// change downwards and the change upwards, either in two values or in one separated by a
/// comma. Only one change is kept for both, see [`crate::dev::AttrChangeEventConfig`], and
/// the smaller one is: an event is then sent at least as often as either asks for.
fn change(values: &Spectrum<str>) -> std::result::Result<Option<f64>, String> {

    let changes = values.iter()
        .flat_map(|value| value.split(','))
        .map(str::trim)
        .filter(|value| !is_unset(value))
        .collect::<Vec<_>>();

    if changes.len() > 2 {
        return Err(format!("expected at most two values, got {}", changes.len()));
    }

    let mut min = None::<f64>;
    for change in changes {
        let change = parse_number(change)?.abs();
        min = Some(min.map_or(change, |min| min.min(change)));
    }

    Ok(min)
    
}

/// A property that is the labels of an enumerated attribute, one value each.
fn labels(values: &Spectrum<str>) -> Vec<Cow<'static, str>> {
    match single(values) {
        Ok(None) => Vec::new(),
        _ => values.iter().map(|label| Cow::Owned(label.to_string())).collect(),
    }
}

/// What the limits of an attribute of that kind are read as: its limits are values of it,
/// so they are of its own type.
fn limit_kind(kind: Option<AttrDataKind>) -> LimitKind {
    match kind {
        Some(AttrDataKind::Short | AttrDataKind::Long | AttrDataKind::Long64 | AttrDataKind::Enum) => LimitKind::Long,
        Some(AttrDataKind::Octet | AttrDataKind::UShort | AttrDataKind::ULong | AttrDataKind::ULong64) => LimitKind::ULong,
        // The floating kinds, and the ones that have no limits to speak of.
        _ => LimitKind::Double,
    }
}

/// The first property of that configuration that an attribute of that kind does not
/// support, see [`ConfigProp::supported_by`].
pub fn unsupported_prop(config: &AttrConfig, kind: Option<AttrDataKind>) -> Option<ConfigProp> {
    ConfigProp::ALL.into_iter().find(|&prop| !prop.supported_by(kind) && !prop_value(config, prop).is_unset())
}

/// Why a property is refused by an attribute of that kind.
pub fn unsupported(kind: Option<AttrDataKind>) -> String {
    match kind {
        Some(kind) => format!("not supported by an attribute of type {kind:?}"),
        None => "not supported by an attribute of no type".to_string(),
    }
}

/// The three kinds of number the limits of an attribute may be read as, see [`limit_kind`].
#[derive(Debug, Clone, Copy)]
enum LimitKind {
    Double,
    Long,
    ULong,
}

// =========================== //
//  Changing the configuration //
// =========================== //

/// What changing the configuration of an attribute on a device does to what the database
/// holds for it on that device, see [`Attr::change_config`].
#[derive(Debug, Default, PartialEq)]
pub struct ConfigChanges {
    /// The properties to store, with their values.
    pub put: Vec<(ConfigProp, Vec<String>)>,
    /// The properties to delete, the device then inheriting them.
    pub del: Vec<ConfigProp>,
}

impl ConfigChanges {
    pub fn is_empty(&self) -> bool {
        self.put.is_empty() && self.del.is_empty()
    }
}

/// Set that property of a configuration to the one of another.
/// 
/// The two halves of the delta alarm only make an alarm together, so a delta time given to
/// a configuration that has no delta value is lost, as it is when it is loaded, see
/// [`ConfigLoader::finish`].
fn copy_prop(dst: &mut AttrConfig, src: &AttrConfig, prop: ConfigProp) {
    match prop {
        ConfigProp::Description => dst.doc = src.doc.clone(),
        ConfigProp::Label => dst.label = src.label.clone(),
        ConfigProp::Unit => dst.unit = src.unit.clone(),
        ConfigProp::StandardUnit => dst.standard_unit = src.standard_unit,
        ConfigProp::DisplayUnit => dst.display_unit = src.display_unit.clone(),
        ConfigProp::Format => dst.display_format = src.display_format.clone(),
        ConfigProp::MinValue => dst.range.min = src.range.min,
        ConfigProp::MaxValue => dst.range.max = src.range.max,
        ConfigProp::MinAlarm => dst.alarm.min = src.alarm.min,
        ConfigProp::MaxAlarm => dst.alarm.max = src.alarm.max,
        ConfigProp::MinWarning => dst.warning.min = src.warning.min,
        ConfigProp::MaxWarning => dst.warning.max = src.warning.max,
        ConfigProp::DeltaVal => {
            let time = dst.delta.and_then(|delta| delta.time);
            dst.delta = src.delta.map(|delta| AttrDeltaConfig { value: delta.value, time });
        }
        ConfigProp::DeltaT => {
            if let Some(delta) = &mut dst.delta {
                delta.time = src.delta.and_then(|delta| delta.time);
            }
        }
        ConfigProp::RelChange => dst.change_event.rel_change = src.change_event.rel_change,
        ConfigProp::AbsChange => dst.change_event.abs_change = src.change_event.abs_change,
        ConfigProp::EventPeriod => dst.periodic_event.period = src.periodic_event.period,
        ConfigProp::ArchiveRelChange => dst.archive_event.rel_change = src.archive_event.rel_change,
        ConfigProp::ArchiveAbsChange => dst.archive_event.abs_change = src.archive_event.abs_change,
        ConfigProp::ArchivePeriod => dst.archive_event.period = src.archive_event.period,
        ConfigProp::EnumLabels => dst.enum_labels = src.enum_labels.clone(),
    }
}

/// What makes that configuration incoherent, if anything: a range whose minimum is not
/// below its maximum, which no value could be in, the way cppTango refuses it.
fn incoherence(config: &AttrConfig) -> Option<String> {
    for (what, range) in [
        ("value", &config.range), 
        ("alarm", &config.alarm), 
        ("warning", &config.warning)
    ] {
        if let (Some(min), Some(max)) = (range.min, range.max) {
            if !(min < max) {
                return Some(format!("the minimum of its {what} range ({min}) is not below its maximum ({max})"));
            }
        }
    }
    None
}

// =========================== //
//      Memorized values       //
// =========================== //

/// The attribute property the memorized value of an attribute is stored under, by the
/// device, see [`Attr::store`].
const MEM_VALUE: &str = "__value";
/// What cppTango stores as the memorized value of an attribute that was never written.
const MEM_NOT_USED: &str = "Not used yet";

/// The string a memorized value is stored as, which is the one cppTango stores, so that a
/// device keeps its set point across servers written in either: a boolean is `true` or
/// `false`, an enumerated value its index, and any other number written out.
/// 
/// Only a scalar can be memorized, see [`super::def::AttrDef::memorized`].
fn mem_value_str(value: &Value) -> std::result::Result<String, String> {
    fn scalar<T: Element + ?Sized>(format: &ValueFormat<T>) -> std::result::Result<T::Ref<'_>, String> {
        format.scalar().map(|scalar| scalar.value()).ok_or_else(|| "only a scalar can be memorized".to_string())
    }
    Ok(match value {
        Value::Bool(format) => scalar(format)?.to_string(),
        Value::Octet(format) => scalar(format)?.to_string(),
        Value::UShort(format) => scalar(format)?.to_string(),
        Value::Short(format) => scalar(format)?.to_string(),
        Value::ULong(format) => scalar(format)?.to_string(),
        Value::Long(format) => scalar(format)?.to_string(),
        Value::ULong64(format) => scalar(format)?.to_string(),
        Value::Long64(format) => scalar(format)?.to_string(),
        Value::Float(format) => scalar(format)?.to_string(),
        Value::Double(format) => scalar(format)?.to_string(),
        Value::Enum(format) => scalar(format)?.0.to_string(),
        Value::String(format) => scalar(format)?.to_string(),
        _ => return Err("a value of that kind cannot be memorized".to_string()),
    })
}

/// The memorized value stored for an attribute of that kind, parsed back, absent for an
/// attribute that was never written, see [`mem_value_str`].
fn parse_mem_value(kind: Option<&AttrDataKind>, values: &Spectrum<str>) -> std::result::Result<Option<Value>, String> {

    let mut iter = values.iter();
    let value = match (iter.next(), iter.next()) {
        (None, _) => return Ok(None),
        (Some(value), None) => value,
        (Some(_), Some(_)) => return Err(format!("expected a single value, got {}", values.len())),
    };

    if value == MEM_NOT_USED {
        return Ok(None);
    }

    // Read the way cppTango reads it, as a stream would: blanks around a number are not
    // part of it, but they are of a string.
    fn parse<T: std::str::FromStr>(value: &str) -> std::result::Result<T, String> {
        value.trim().parse::<T>().map_err(|_| format!("{value:?} is not a value of the attribute"))
    }

    Ok(Some(match kind {
        Some(AttrDataKind::Bool) => match value.trim() {
            value if value.eq_ignore_ascii_case("true") || value == "1" => Value::from(true),
            value if value.eq_ignore_ascii_case("false") || value == "0" => Value::from(false),
            _ => return Err(format!("{value:?} is not a boolean")),
        },
        Some(AttrDataKind::Octet) => Value::from(parse::<u8>(value)?),
        Some(AttrDataKind::UShort) => Value::from(parse::<u16>(value)?),
        Some(AttrDataKind::Short) => Value::from(parse::<i16>(value)?),
        Some(AttrDataKind::ULong) => Value::from(parse::<u32>(value)?),
        Some(AttrDataKind::Long) => Value::from(parse::<i32>(value)?),
        Some(AttrDataKind::ULong64) => Value::from(parse::<u64>(value)?),
        Some(AttrDataKind::Long64) => Value::from(parse::<i64>(value)?),
        Some(AttrDataKind::Float) => Value::from(parse::<f32>(value)?),
        Some(AttrDataKind::Double) => Value::from(parse::<f64>(value)?),
        Some(AttrDataKind::Enum) => Value::from(DevEnum(parse::<i16>(value)?)),
        Some(AttrDataKind::String) => Value::from(value),
        _ => return Err("a value of that kind cannot be memorized".to_string()),
    }))

}

#[cfg(test)]
mod tests {

    use crate::dev::{AttrRangeConfig, AttrChangeEventConfig};

    use super::*;

    /// An attribute whose definition gives it a label, whose class is given a unit by the
    /// database, and which has a unit and a lower bound of its own on its device.
    fn current() -> AttrConfig {
        AttrConfig {
            label: Some("Position".into()),
            unit: Some("cm".into()),
            range: AttrRangeConfig { min: Some(AttrNumber::Long(-5)), max: None },
            ..AttrConfig::default()
        }
    }

    /// The changes of that attribute to the configuration the given function makes of the
    /// one it has, along with the configuration it ends up with.
    fn changes(change: impl FnOnce(&mut AttrConfig)) -> (ConfigChanges, AttrConfig) {
        let attr = Attr::new(Arc::new(AttrDef::<()>::new("Position").kind(AttrDataKind::Long).label("Position")));
        attr.setup.lock().unwrap().config = current();
        let class = [Named::new("unit".into(), Spectrum::from_strs(["mm"]).unwrap())];
        let mut requested = current();
        change(&mut requested);
        let changes = attr.change_config(&class, &requested).unwrap();
        (changes, attr.config())
    }

    fn put(pairs: &[(ConfigProp, &str)]) -> ConfigChanges {
        ConfigChanges {
            put: pairs.iter().map(|&(prop, value)| (prop, vec![value.to_string()])).collect(),
            del: Vec::new(),
        }
    }

    fn del(props: &[ConfigProp]) -> ConfigChanges {
        ConfigChanges { put: Vec::new(), del: props.to_vec() }
    }

    /// Numbers against a range whose bounds are of another variant, the widest integers
    /// compared exactly, and a not-a-number outside of any range.
    #[test]
    fn range_bounds() {
        let range = AttrRangeConfig { min: Some(AttrNumber::Long(-1)), max: Some(AttrNumber::Double(2.5)) };
        assert!(!outside(&range, AttrNumber::ULong(2)));
        assert!(!outside(&range, AttrNumber::Long(-1)));
        assert!(outside(&range, AttrNumber::ULong(3)));
        assert!(outside(&range, AttrNumber::Double(f64::NAN)));
        let range = AttrRangeConfig { min: None, max: Some(AttrNumber::ULong(u64::MAX - 1)) };
        assert!(outside(&range, AttrNumber::ULong(u64::MAX)));
        assert!(!outside(&range, AttrNumber::Long(i64::MIN)));
        assert!(!any_number(&Value::from("text"), |_| true));
    }

    /// A range whose minimum is not below its maximum, an empty one included, and a range
    /// open on either side.
    #[test]
    fn range_incoherence() {
        let range = |min: i64, max: i64| AttrRangeConfig { min: Some(AttrNumber::Long(min)), max: Some(AttrNumber::Long(max)) };
        assert_eq!(incoherence(&AttrConfig { range: range(-1, 1), ..AttrConfig::default() }), None);
        assert!(incoherence(&AttrConfig { warning: range(1, 1), ..AttrConfig::default() }).unwrap().contains("warning"));
        assert!(incoherence(&AttrConfig { alarm: range(2, 1), ..AttrConfig::default() }).unwrap().contains("alarm"));
        let open = AttrRangeConfig { min: Some(AttrNumber::Long(1)), max: None };
        assert_eq!(incoherence(&AttrConfig { range: open, ..AttrConfig::default() }), None);
    }

    /// A value: stored, unless it is what the device has already, or what it inherits.
    #[test]
    fn value_changes() {
        assert_eq!(changes(|_| ()).0, ConfigChanges::default());
        assert_eq!(changes(|config| config.label = Some("Pos".into())).0, put(&[(ConfigProp::Label, "Pos")]));
        assert_eq!(changes(|config| config.range.max = Some(AttrNumber::Long(5))).0, put(&[(ConfigProp::MaxValue, "5")]));
        assert_eq!(changes(|config| config.unit = Some("mm".into())).0, del(&[ConfigProp::Unit]));
    }

    /// No value: what the device inherits, whatever it is, and nothing to do for a field
    /// the device has nothing of its own for.
    #[test]
    fn reset_changes() {
        let (unit, config) = changes(|config| config.unit = None);
        assert_eq!((unit, config.unit.as_deref()), (del(&[ConfigProp::Unit]), Some("mm")));
        let (min, config) = changes(|config| config.range.min = None);
        assert_eq!((min, config.range.min), (del(&[ConfigProp::MinValue]), None));
        let (label, config) = changes(|config| config.label = None);
        assert_eq!((label, config.label.as_deref()), (ConfigChanges::default(), Some("Position")));
    }

    /// The bounds of a string, refused unless unset, and the alarms of an enumerated
    /// attribute, refused when its range is not.
    #[test]
    fn unsupported_props() {
        let load = |kind, name: &str, value: &str| {
            let props = [Named::new(name.into(), Spectrum::from_strs([value]).unwrap())];
            let mut loader = ConfigLoader::new(&AttrConfig::default(), Some(kind));
            loader.apply_level("device", Ok(&props));
            loader.finish().1
        };
        assert!(load(AttrDataKind::String, "max_alarm", "5").unwrap().contains("not supported by an attribute of type String"));
        assert_eq!(load(AttrDataKind::String, "max_alarm", "Not specified"), None);
        assert_eq!(load(AttrDataKind::String, "label", "Name"), None);
        assert!(load(AttrDataKind::Enum, "max_alarm", "2").is_some());
        assert_eq!(load(AttrDataKind::Enum, "max_value", "2"), None);
    }

    /// Every field of a configuration stored and loaded back the same.
    #[test]
    fn prop_round_trip() {

        let config = AttrConfig {
            doc: Some("First line\nSecond line".into()),
            standard_unit: Some(0.001),
            range: AttrRangeConfig { min: Some(AttrNumber::Long(-5)), max: Some(AttrNumber::Long(5)) },
            delta: Some(AttrDeltaConfig { value: AttrNumber::Long(1), time: Some(Duration::from_millis(250)) }),
            change_event: AttrChangeEventConfig { rel_change: Some(0.5), abs_change: None },
            enum_labels: vec!["Off".into(), "On".into()],
            ..AttrConfig::default()
        };

        let attr = Attr::new(Arc::new(AttrDef::<()>::new("Position").kind(AttrDataKind::Long)));
        let changes = attr.change_config(&[], &config).unwrap();
        assert_eq!(attr.config(), config);
        let props = changes.put.into_iter()
            .map(|(prop, values)| Named::new(prop.name().into(), Spectrum::from_strs(values).unwrap()))
            .collect::<Vec<_>>();

        let mut loader = ConfigLoader::new(&AttrConfig::default(), Some(AttrDataKind::Long));
        loader.apply_level("device", Ok(&props));
        assert_eq!(loader.finish(), (config, None));

    }

}