aboutsummaryrefslogtreecommitdiff
path: root/src/subscription.rs
blob: 135996b32a87c2118400a0a9edee6ece42847932 (plain)
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
use crate::subscription_listener::SubscriptionListener;
use std::collections::HashMap;
use std::error::Error;
use std::fmt::{self, Debug, Formatter};

/// Enum representing the snapshot delivery preferences to be requested to Lightstreamer Server for the items in the Subscription.
#[derive(Debug, Default)]
pub enum Snapshot {
    Yes,
    No,
    Number(usize),
    #[default]
    None,
}

impl Default for &Snapshot {
    fn default() -> Self {
        &Snapshot::None
    }
}

impl ToString for Snapshot {
    fn to_string(&self) -> String {
        match self {
            Snapshot::Yes => "true".to_string(),
            Snapshot::No => "false".to_string(),
            Snapshot::Number(n) => n.to_string(),
            Snapshot::None => "none".to_string(),
        }
    }
}

/// Enum representing the subscription mode.
#[derive(Debug, PartialEq, Eq)]
pub enum SubscriptionMode {
    Merge,
    Distinct,
    Raw,
    Command,
}

impl ToString for SubscriptionMode {
    fn to_string(&self) -> String {
        match self {
            SubscriptionMode::Merge => "MERGE".to_string(),
            SubscriptionMode::Distinct => "DISTINCT".to_string(),
            SubscriptionMode::Raw => "RAW".to_string(),
            SubscriptionMode::Command => "COMMAND".to_string(),
        }
    }
}

/// Struct representing a Subscription to be submitted to a Lightstreamer Server.
/// It contains subscription details and the listeners needed to process the real-time data.
pub struct Subscription {
    /// The subscription mode for the items, required by Lightstreamer Server.
    mode: SubscriptionMode,
    /// An array of items to be subscribed to through Lightstreamer server.
    items: Option<Vec<String>>,
    /// An "Item Group" identifier representing a list of items.
    item_group: Option<String>,
    /// An array of fields for the items to be subscribed to through Lightstreamer Server.
    fields: Option<Vec<String>>,
    /// A "Field Schema" identifier representing a list of fields.
    field_schema: Option<String>,
    /// The name of the Data Adapter that supplies all the items for this Subscription.
    data_adapter: Option<String>,
    /// The name of the second-level Data Adapter for a COMMAND Subscription.
    command_second_level_data_adapter: Option<String>,
    /// The "Field List" to be subscribed to through Lightstreamer Server for the second-level items in a COMMAND Subscription.
    command_second_level_fields: Option<Vec<String>>,
    /// The "Field Schema" to be subscribed to through Lightstreamer Server for the second-level items in a COMMAND Subscription.
    command_second_level_field_schema: Option<String>,
    /// The length to be requested to Lightstreamer Server for the internal queuing buffers for the items in the Subscription.
    requested_buffer_size: Option<usize>,
    /// The maximum update frequency to be requested to Lightstreamer Server for all the items in the Subscription.
    requested_max_frequency: Option<f64>,
    /// The snapshot delivery preferences to be requested to Lightstreamer Server for the items in the Subscription.
    requested_snapshot: Option<Snapshot>,
    /// The selector name for all the items in the Subscription, used as a filter on the updates received.
    selector: Option<String>,
    /// A list of SubscriptionListener instances that will receive events from this Subscription.
    listeners: Vec<Box<dyn SubscriptionListener>>,
    /// A HashMap storing the latest values received for each item/field pair.
    values: HashMap<(usize, usize), String>,
    /// A HashMap storing the latest values received for each key/field pair in a COMMAND Subscription.
    command_values: HashMap<String, HashMap<usize, String>>,
    /// A flag indicating whether the Subscription is currently active or not.
    is_active: bool,
    /// A flag indicating whether the Subscription is currently subscribed to through the server or not.
    is_subscribed: bool,
}

impl Subscription {
    /// Constructor for creating a new Subscription instance.
    ///
    /// # Parameters
    /// - `mode`: The subscription mode for the items, required by Lightstreamer Server.
    /// - `items`: An array of items to be subscribed to through Lightstreamer server. It is also possible to specify the "Item List" or "Item Group" later.
    /// - `fields`: An array of fields for the items to be subscribed to through Lightstreamer Server. It is also possible to specify the "Field List" or "Field Schema" later.
    ///
    /// # Errors
    /// Returns an error if no items or fields are provided.
    pub fn new(
        mode: SubscriptionMode,
        items: Option<Vec<String>>,
        fields: Option<Vec<String>>,
    ) -> Result<Subscription, Box<dyn Error>> {
        if items.is_none() || fields.is_none() {
            return Err("Items and fields must be provided".to_string().into());
        }

        Ok(Subscription {
            mode,
            items,
            item_group: None,
            fields,
            field_schema: None,
            data_adapter: None,
            command_second_level_data_adapter: None,
            command_second_level_fields: None,
            command_second_level_field_schema: None,
            requested_buffer_size: None,
            requested_max_frequency: None,
            requested_snapshot: None,
            selector: None,
            listeners: Vec::new(),
            values: HashMap::new(),
            command_values: HashMap::new(),
            is_active: false,
            is_subscribed: false,
        })
    }

    /// Adds a listener that will receive events from the Subscription instance.
    ///
    /// The same listener can be added to several different Subscription instances.
    ///
    /// # Lifecycle
    /// A listener can be added at any time. A call to add a listener already present will be ignored.
    ///
    /// # Parameters
    /// - `listener`: An object that will receive the events as documented in the SubscriptionListener interface.
    ///
    /// # See also
    /// `removeListener()`
    pub fn add_listener(&mut self, listener: Box<dyn SubscriptionListener>) {
        self.listeners.push(listener);
    }

    /// Removes a listener from the Subscription instance so that it will not receive events anymore.
    ///
    /// # Lifecycle
    /// A listener can be removed at any time.
    ///
    /// # Parameters
    /// - `listener`: The listener to be removed.
    ///
    /// # See also
    /// `addListener()`
    pub fn remove_listener<T>(&mut self, listener: &T)
    where
        T: SubscriptionListener,
    {
        self.listeners.retain(|l| {
            let l_ref = l.as_ref() as &dyn SubscriptionListener;
            let listener_ref = listener as &dyn SubscriptionListener;
            !(std::ptr::addr_of!(*l_ref) == std::ptr::addr_of!(*listener_ref))
        });
    }

    /// Returns a list containing the SubscriptionListener instances that were added to this client.
    ///
    /// # Returns
    /// A list containing the listeners that were added to this client.
    ///
    /// # See also
    /// `addListener()`
    pub fn get_listeners(&self) -> &Vec<Box<dyn SubscriptionListener>> {
        &self.listeners
    }

    /// Inquiry method that can be used to read the mode specified for this Subscription.
    ///
    /// # Lifecycle
    /// This method can be called at any time.
    ///
    /// # Returns
    /// The Subscription mode specified in the constructor.
    pub fn get_mode(&self) -> &SubscriptionMode {
        &self.mode
    }

    /// Setter method that sets the "Item Group" to be subscribed to through Lightstreamer Server.
    ///
    /// Any call to this method will override any "Item List" or "Item Group" previously specified.
    ///
    /// # Lifecycle
    /// This method can only be called while the Subscription instance is in its "inactive" state.
    ///
    /// # Errors
    /// Returns an error if the Subscription is currently "active".
    ///
    /// # Parameters
    /// - `group`: A String to be expanded into an item list by the Metadata Adapter.
    pub fn set_item_group(&mut self, group: String) -> Result<(), String> {
        if self.is_active {
            return Err("Subscription is active. This method can only be called while the Subscription instance is in its 'inactive' state.".to_string());
        }
        self.item_group = Some(group);
        Ok(())
    }

    /// Inquiry method that can be used to read the item group specified for this Subscription.
    ///
    /// # Lifecycle
    /// This method can only be called if the Subscription has been initialized using an "Item Group"
    ///
    /// # Returns
    /// The "Item Group" to be subscribed to through the server, or `None` if the Subscription was initialized with an "Item List" or was not initialized at all.
    pub fn get_item_group(&self) -> Option<&String> {
        self.item_group.as_ref()
    }

    /// Setter method that sets the "Item List" to be subscribed to through Lightstreamer Server.
    ///
    /// Any call to this method will override any "Item List" or "Item Group" previously specified.
    ///
    /// # Lifecycle
    /// This method can only be called while the Subscription instance is in its "inactive" state.
    ///
    /// # Errors
    /// - Returns an error if the Subscription is currently "active".
    /// - Returns an error if any of the item names in the "Item List" contains a space, is a number, or is empty/None.
    ///
    /// # Parameters
    /// - `items`: An array of items to be subscribed to through the server.
    pub fn set_items(&mut self, items: Vec<String>) -> Result<(), String> {
        if self.is_active {
            return Err("Subscription is active".to_string());
        }
        for item in &items {
            if item.contains(" ") || item.parse::<usize>().is_ok() || item.is_empty() {
                return Err("Invalid item name".to_string());
            }
        }
        self.items = Some(items);
        Ok(())
    }

    /// Inquiry method that can be used to read the "Item List" specified for this Subscription.
    /// Note that if the single-item-constructor was used, this method will return an array of length 1 containing such item.
    ///
    /// # Lifecycle
    /// This method can only be called if the Subscription has been initialized with an "Item List".
    ///
    /// # Returns
    /// The "Item List" to be subscribed to through the server, or `None` if the Subscription was initialized with an "Item Group" or was not initialized at all.
    pub fn get_items(&self) -> Option<&Vec<String>> {
        self.items.as_ref()
    }

    /// Setter method that sets the "Field Schema" to be subscribed to through Lightstreamer Server.
    ///
    /// Any call to this method will override any "Field List" or "Field Schema" previously specified.
    ///
    /// # Lifecycle
    /// This method can only be called while the Subscription instance is in its "inactive" state.
    ///
    /// # Errors
    /// Returns an error if the Subscription is currently "active".
    ///
    /// # Parameters
    /// - `schema`: A String to be expanded into a field list by the Metadata Adapter.
    pub fn set_field_schema(&mut self, schema: String) -> Result<(), String> {
        if self.is_active {
            return Err("Subscription is active".to_string());
        }
        self.field_schema = Some(schema);
        Ok(())
    }

    /// Inquiry method that can be used to read the field schema specified for this Subscription.
    ///
    /// # Lifecycle
    /// This method can only be called if the Subscription has been initialized using a "Field Schema"
    ///
    /// # Returns
    /// The "Field Schema" to be subscribed to through the server, or `None` if the Subscription was initialized with a "Field List" or was not initialized at all.
    pub fn get_field_schema(&self) -> Option<&String> {
        self.field_schema.as_ref()
    }

    /// Setter method that sets the "Field List" to be subscribed to through Lightstreamer Server.
    ///
    /// Any call to this method will override any "Field List" or "Field Schema" previously specified.
    ///
    /// # Lifecycle
    /// This method can only be called while the Subscription instance is in its "inactive" state.
    ///
    /// # Errors
    /// - Returns an error if the Subscription is currently "active".
    /// - Returns an error if any of the field names in the list contains a space or is empty/None.
    ///
    /// # Parameters
    /// - `fields`: An array of fields to be subscribed to through the server.
    pub fn set_fields(&mut self, fields: Vec<String>) -> Result<(), String> {
        if self.is_active {
            return Err("Subscription is active".to_string());
        }
        for field in &fields {
            if field.contains(" ") || field.is_empty() {
                return Err("Invalid field name".to_string());
            }
        }
        self.fields = Some(fields);
        Ok(())
    }

    /// Inquiry method that can be used to read the "Field List" specified for this Subscription.
    ///
    /// # Lifecycle
    /// This method can only be called if the Subscription has been initialized using a "Field List".
    ///
    /// # Returns
    /// The "Field List" to be subscribed to through the server, or `None` if the Subscription was initialized with a "Field Schema" or was not initialized at all.
    pub fn get_fields(&self) -> Option<&Vec<String>> {
        self.fields.as_ref()
    }

    /// Setter method that sets the name of the Data Adapter (within the Adapter Set used by the current session) that supplies all the items for this Subscription.
    ///
    /// The Data Adapter name is configured on the server side through the "name" attribute of the `<data_provider>` element, in the "adapters.xml" file that defines the Adapter Set (a missing attribute configures the "DEFAULT" name).
    ///
    /// Note that if more than one Data Adapter is needed to supply all the items in a set of items, then it is not possible to group all the items of the set in a single Subscription. Multiple Subscriptions have to be defined.
    ///
    /// # Default
    /// The default Data Adapter for the Adapter Set, configured as "DEFAULT" on the Server.
    ///
    /// # Lifecycle
    /// This method can only be called while the Subscription instance is in its "inactive" state.
    ///
    /// # Errors
    /// Returns an error if the Subscription is currently "active".
    ///
    /// # Parameters
    /// - `adapter`: The name of the Data Adapter. A `None` value is equivalent to the "DEFAULT" name.
    ///
    /// # See also
    /// `ConnectionDetails.setAdapterSet()`
    pub fn set_data_adapter(&mut self, adapter: Option<String>) -> Result<(), String> {
        if self.is_active {
            return Err("Subscription is active".to_string());
        }
        self.data_adapter = adapter;
        Ok(())
    }

    /// Inquiry method that can be used to read the name of the Data Adapter specified for this Subscription through `setDataAdapter()`.
    ///
    /// # Lifecycle
    /// This method can be called at any time.
    ///
    /// # Returns
    /// The name of the Data Adapter; returns `None` if no name has been configured, so that the "DEFAULT" Adapter Set is used.
    pub fn get_data_adapter(&self) -> Option<&String> {
        self.data_adapter.as_ref()
    }

    /// Setter method that sets the name of the second-level Data Adapter (within the Adapter Set used by the current session)
    /// Setter method that sets the name of the second-level Data Adapter (within the Adapter Set used by the current session) that supplies all the second-level items for a COMMAND Subscription.
    ///
    /// All the possible second-level items should be supplied in "MERGE" mode with snapshot available.
    ///
    /// The Data Adapter name is configured on the server side through the "name" attribute of the `<data_provider>` element, in the "adapters.xml" file that defines the Adapter Set (a missing attribute configures the "DEFAULT" name).
    ///
    /// # Default
    /// The default Data Adapter for the Adapter Set, configured as "DEFAULT" on the Server.
    ///
    /// # Lifecycle
    /// This method can only be called while the Subscription instance is in its "inactive" state.
    ///
    /// # Errors
    /// - Returns an error if the Subscription is currently "active".
    /// - Returns an error if the Subscription mode is not "COMMAND".
    ///
    /// # Parameters
    /// - `adapter`: The name of the Data Adapter. A `None` value is equivalent to the "DEFAULT" name.
    ///
    /// # See also
    /// `Subscription.setCommandSecondLevelFields()`
    ///
    /// # See also
    /// `Subscription.setCommandSecondLevelFieldSchema()`
    pub fn set_command_second_level_data_adapter(
        &mut self,
        adapter: Option<String>,
    ) -> Result<(), String> {
        if self.is_active {
            return Err("Subscription is active".to_string());
        }
        if self.mode != SubscriptionMode::Command {
            return Err("Subscription mode is not Command".to_string());
        }
        self.command_second_level_data_adapter = adapter;
        Ok(())
    }

    /// Inquiry method that can be used to read the name of the second-level Data Adapter specified for this Subscription through `setCommandSecondLevelDataAdapter()`.
    ///
    /// # Lifecycle
    /// This method can be called at any time.
    ///
    /// # Errors
    /// Returns an error if the Subscription mode is not COMMAND.
    ///
    /// # Returns
    /// The name of the second-level Data Adapter.
    ///
    /// # See also
    /// `setCommandSecondLevelDataAdapter()`
    pub fn get_command_second_level_data_adapter(&self) -> Option<&String> {
        if self.mode != SubscriptionMode::Command {
            return None;
        }
        self.command_second_level_data_adapter.as_ref()
    }

    /// Setter method that sets the "Field Schema" to be subscribed to through Lightstreamer Server for the second-level items. It can only be used on COMMAND Subscriptions.
    ///
    /// Any call to this method will override any "Field List" or "Field Schema" previously specified for the second-level.
    ///
    /// Calling this method enables the two-level behavior:
    ///
    /// In synthesis, each time a new key is received on the COMMAND Subscription, the key value is treated as an Item name and an underlying Subscription for this Item is created and subscribed to automatically, to feed fields specified by this method. This mono-item Subscription is specified through an "Item List" containing only the Item name received. As a consequence, all the conditions provided for subscriptions through Item Lists have to be satisfied. The item is subscribed to in "MERGE" mode, with snapshot request and with the same maximum frequency setting as for the first-level items (including the "unfiltered" case). All other Subscription properties are left as the default. When the key is deleted by a DELETE command on the first-level Subscription, the associated second-level Subscription is also unsubscribed from.
    ///
    /// Specify `None` as parameter will disable the two-level behavior.
    ///
    /// # Lifecycle
    /// This method can only be called while the Subscription instance is in its "inactive" state.
    ///
    /// # Errors
    /// - Returns an error if the Subscription is currently "active".
    /// - Returns an error if the Subscription mode is not "COMMAND".
    ///
    /// # Parameters
    /// - `schema`: A String to be expanded into a field list by the Metadata Adapter.
    ///
    /// # See also
    /// `Subscription.setCommandSecondLevelFields()`
    pub fn set_command_second_level_field_schema(
        &mut self,
        schema: Option<String>,
    ) -> Result<(), String> {
        if self.is_active {
            return Err("Subscription is active".to_string());
        }
        if self.mode != SubscriptionMode::Command {
            return Err("Subscription mode is not Command".to_string());
        }
        self.command_second_level_field_schema = schema;
        Ok(())
    }

    /// Inquiry method that can be used to read the "Field Schema" specified for second-level Subscriptions.
    ///
    /// # Lifecycle
    /// This method can only be called if the second-level of this Subscription has been initialized using a "Field Schema".
    ///
    /// # Errors
    /// Returns an error if the Subscription mode is not COMMAND.
    ///
    /// # Returns
    /// The "Field Schema" to be subscribed to through the server, or `None` if the Subscription was initialized with a "Field List" or was not initialized at all.
    ///
    /// # See also
    /// `Subscription.setCommandSecondLevelFieldSchema()`
    pub fn get_command_second_level_field_schema(&self) -> Option<&String> {
        if self.mode != SubscriptionMode::Command {
            return None;
        }
        self.command_second_level_field_schema.as_ref()
    }

    /// Setter method that sets the "Field List" to be subscribed to through Lightstreamer Server for the second-level items. It can only be used on COMMAND Subscriptions.
    ///
    /// Any call to this method will override any "Field List" or "Field Schema" previously specified for the second-level.
    ///
    /// Calling this method enables the two-level behavior:
    ///
    /// In synthesis, each time a new key is received on the COMMAND Subscription, the key value is treated as an Item name and an underlying Subscription for this Item is created and subscribed to automatically, to feed fields specified by this method. This mono-item Subscription is specified through an "Item List" containing only the Item name received. As a consequence, all the conditions provided for subscriptions through Item Lists have to be satisfied. The item is subscribed to in "MERGE" mode, with snapshot request and with the same maximum frequency setting as for the first-level items (including the "unfiltered" case). All other Subscription properties are left as the default. When the key is deleted by a DELETE command on the first-level Subscription, the associated second-level Subscription is also unsubscribed from.
    ///
    /// Specifying `None` as parameter will disable the two-level behavior.
    ///
    /// # Lifecycle
    /// This method can only be called while the Subscription instance is in its "inactive" state.
    ///
    /// # Errors
    /// - Returns an error if the Subscription is currently "active".
    /// - Returns an error if the Subscription mode is not "COMMAND".
    /// - Returns an error if any of the field names in the "Field List" contains a space or is empty/None.
    ///
    /// # Parameters
    /// - `fields`: An array of Strings containing a list of fields to be subscribed to through the server. Ensure that no name conflict is generated between first-level and second-level fields. In case of conflict, the second-level field will not be accessible by name, but only by position.
    ///
    /// # See also
    /// `Subscription.setCommandSecondLevelFieldSchema()`
    pub fn set_command_second_level_fields(
        &mut self,
        fields: Option<Vec<String>>,
    ) -> Result<(), String> {
        if self.is_active {
            return Err("Subscription is active".to_string());
        }
        if self.mode != SubscriptionMode::Command {
            return Err("Subscription mode is not Command".to_string());
        }
        if let Some(ref fields) = fields {
            for field in fields {
                if field.contains(" ") || field.is_empty() {
                    return Err("Invalid field name".to_string());
                }
            }
        }
        self.command_second_level_fields = fields;
        Ok(())
    }

    /// Inquiry method that can be used to read the "Field List" specified for second-level Subscriptions.
    ///
    /// # Lifecycle
    /// This method can only be called if the second-level of this Subscription has been initialized using a "Field List"
    ///
    /// # Errors
    /// Returns an error if the Subscription mode is not COMMAND.
    ///
    /// # Returns
    /// The list of fields to be subscribed to through the server, or `None` if the Subscription was initialized with a "Field Schema" or was not initialized at all.
    ///
    /// # See also
    /// `Subscription.setCommandSecondLevelFields()`
    pub fn get_command_second_level_fields(&self) -> Option<&Vec<String>> {
        if self.mode != SubscriptionMode::Command {
            return None;
        }
        self.command_second_level_fields.as_ref()
    }

    /// Setter method that sets the length to be requested to Lightstreamer Server for the internal queuing buffers for the items in the Subscription. A Queuing buffer is used by the Server to accumulate a burst of updates for an item, so that they can all be sent to the client, despite of bandwidth or frequency limits. It can be used only when the subscription mode is MERGE or DISTINCT and unfiltered dispatching has not been requested. Note that the Server may pose an upper limit on the size of its internal buffers.
    ///
    /// # Default
    /// `None`, meaning to lean on the Server default based on the subscription mode. This means that the buffer size will be 1 for MERGE subscriptions and "unlimited" for DISTINCT subscriptions. See the "General Concepts" document for further details.
    ///
    /// # Lifecycle
    /// This method can only be called while the Subscription instance is in its "inactive" state.
    ///
    /// # Errors
    /// - Returns an error if the Subscription is currently "active".
    /// - Returns an error if the specified value is not `None` nor "unlimited" nor a valid positive integer number.
    ///
    /// # Parameters
    /// - `size`: An integer number, representing the length of the internal queuing buffers to be used in the Server. If the string "unlimited" is supplied, then no buffer size limit is requested (the check is case insensitive). It is also possible to supply a `None` value to stick to the Server default (which currently depends on the subscription mode).
    ///
    /// # See also
    /// `Subscription.setRequestedMaxFrequency()`
    pub fn set_requested_buffer_size(&mut self, size: Option<usize>) -> Result<(), String> {
        if self.is_active {
            return Err("Subscription is active".to_string());
        }
        self.requested_buffer_size = size;
        Ok(())
    }

    /// Inquiry method that can be used to read the buffer size, configured though `setRequestedBufferSize()`, to be requested to the Server for this Subscription.
    ///
    /// # Lifecycle
    /// This method can be called at any time.
    ///
    /// # Returns
    /// An integer number, representing the buffer size to be requested to the server, or the string "unlimited", or `None`.
    pub fn get_requested_buffer_size(&self) -> Option<&usize> {
        self.requested_buffer_size.as_ref()
    }

    /// Setter method that sets the maximum update frequency to be requested to Lightstreamer Server for all the items in the Subscription. It can be used only if the Subscription mode is MERGE, DISTINCT or COMMAND (in the latter case, the frequency limitation applies to the UPDATE events for each single key). For Subscriptions with two-level behavior (see `Subscription.setCommandSecondLevelFields()` and `Subscription.setCommandSecondLevelFieldSchema()`), the specified frequency limit applies to both first-level and second-level items.
    ///
    /// Note that frequency limits on the items can also be set on the server side and this request can only be issued in order to furtherly reduce the frequency, not to rise it beyond these limits.
    ///
    /// This method can also be used to request unfiltered dispatching for the items in the Subscription. However, unfiltered dispatching requests may be refused if any frequency limit is posed on the server side for some item.
    ///
    /// # General Edition Note
    /// A further global frequency limit could also be imposed by the Server, depending on Edition and License Type; this specific limit also applies to RAW mode and to unfiltered dispatching. To know what features are enabled by your license, please see the License tab of the Monitoring Dashboard (by default, available at /dashboard).
    ///
    /// # Default
    /// `None`, meaning to lean on the Server default based on the subscription mode. This consists, for all modes, in not applying any frequency limit to the subscription (the same as "unlimited"); see the "General Concepts" document for further details.
    ///
    /// # Lifecycle
    /// This method can can be called at any time with some differences based on the Subscription status:
    ///
    /// - If the Subscription instance is in its "inactive" state then this method can be called at will.
    ///
    /// - If the Subscription instance is in its "active" state then the method can still be called unless the current value is "unfiltered" or the supplied value is "unfiltered" or `None`. If the Subscription instance is in its "active" state and the connection to the server is currently open, then a request to change the frequency of the Subscription on the fly is sent to the server.
    ///
    /// # Errors
    /// - Returns an error if the Subscription is currently "active" and the current value of this property is "unfiltered".
    /// - Returns an error if the Subscription is currently "active" and the given parameter is `None` or "unfiltered".
    /// - Returns an error if the specified value is not `None` nor one of the special "unlimited" and "unfiltered" values nor a valid positive number.
    ///
    /// # Parameters
    /// - `freq`: A decimal number, representing the maximum update frequency (expressed in updates per second) for each item in the Subscription; for instance, with a setting of 0.5, for each single item, no more than one update every 2 seconds will be received. If the string "unlimited" is supplied, then no frequency limit is requested. It is also possible to supply the string "unfiltered", to ask for unfiltered dispatching, if it is allowed for the items, or a `None` value to stick to the Server default (which currently corresponds to "unlimited"). The check for the string constants is case insensitive.
    pub fn set_requested_max_frequency(&mut self, freq: Option<f64>) -> Result<(), String> {
        if self.is_active && self.requested_max_frequency.is_none() {
            return Err("Subscription is active and current value is unfiltered".to_string());
        }
        if self.is_active && freq.is_none() {
            return Err("Cannot set unfiltered while active".to_string());
        }
        if self.is_active && freq.is_none() {
            return Err("Cannot set None while active".to_string());
        }
        self.requested_max_frequency = freq;
        Ok(())
    }

    /// Inquiry method that can be used to read the max frequency, configured through `setRequestedMaxFrequency()`, to be requested to the Server for this Subscription.
    ///
    /// # Lifecycle
    /// This method can be called at any time.
    ///
    /// # Returns
    /// A decimal number, representing the max frequency to be requested to the server (expressed in updates per second), or the strings "unlimited" or "unfiltered", or `None`.
    pub fn get_requested_max_frequency(&self) -> Option<&f64> {
        self.requested_max_frequency.as_ref()
    }

    /// Setter method that enables/disables snapshot delivery request for the items in the Subscription. The snapshot can be requested only if the Subscription mode is MERGE, DISTINCT or COMMAND.
    ///
    /// # Default
    /// "yes" if the Subscription mode is not "RAW", `None` otherwise.
    ///
    /// # Lifecycle
    /// This method can only be called while the Subscription instance is in its "inactive" state.
    ///
    /// # Errors
    /// - Returns an error if the Subscription is currently "active".
    /// - Returns an error if the specified value is not "yes" nor "no" nor `None` nor a valid integer positive number.
    /// - Returns an error if the specified value is not compatible with the mode of the Subscription:
    ///     - In case of a RAW Subscription only `None` is a valid value;
    ///     - In case of a non-DISTINCT Subscription only `None` "yes" and "no" are valid values.
    ///
    /// # Parameters
    /// - `snapshot`: "yes"/"no" to request/not request snapshot delivery (the check is case insensitive). If the Subscription mode is DISTINCT, instead of "yes", it is also possible to supply an integer number, to specify the requested length of the snapshot (though the length of the received snapshot may be less than
    /// requested, because of insufficient data or server side limits); passing "yes" means that the snapshot length should be determined only by the Server. `None` is also a valid value; if specified, no snapshot preference will be sent to the server that will decide itself whether or not to send any snapshot.
    ///
    /// # See also
    /// `ItemUpdate.isSnapshot()`
    pub fn set_requested_snapshot(&mut self, snapshot: Option<Snapshot>) -> Result<(), String> {
        if self.is_active {
            return Err("Subscription is active".to_string());
        }
        match snapshot {
            Some(Snapshot::None) => {
                if self.mode == SubscriptionMode::Raw {
                    return Err("Cannot request snapshot for Raw mode".to_string());
                }
            }
            Some(Snapshot::Number(_)) => {
                if self.mode != SubscriptionMode::Distinct {
                    return Err("Cannot specify snapshot length for non-Distinct mode".to_string());
                }
            }
            _ => {}
        }
        self.requested_snapshot = snapshot;
        Ok(())
    }

    /// Inquiry method that can be used to read the snapshot preferences, configured through `setRequestedSnapshot()`, to be requested to the Server for this Subscription.
    ///
    /// # Lifecycle
    /// This method can be called at any time.
    ///
    /// # Returns
    /// "yes", "no", `None`, or an integer number.
    pub fn get_requested_snapshot(&self) -> Option<&Snapshot> {
        self.requested_snapshot.as_ref()
    }

    /// Setter method that sets the selector name for all the items in the Subscription. The selector is a filter on the updates received. It is executed on the Server and implemented by the Metadata Adapter.
    ///
    /// # Default
    /// `None` (no selector).
    ///
    /// # Lifecycle
    /// This method can only be called while the Subscription instance is in its "inactive" state.
    ///
    /// # Errors
    /// Returns an error if the Subscription is currently "active".
    ///
    /// # Parameters
    /// - `selector`: The name of a selector, to be recognized by the Metadata Adapter, or `None` to unset the selector.
    pub fn set_selector(&mut self, selector: Option<String>) -> Result<(), String> {
        if self.is_active {
            return Err("Subscription is active".to_string());
        }
        self.selector = selector;
        Ok(())
    }

    /// Inquiry method that can be used to read the selector name specified for this Subscription through `setSelector()`.
    ///
    /// # Lifecycle
    /// This method can be called at any time.
    ///
    /// # Returns
    /// The name of the selector.
    pub fn get_selector(&self) -> Option<&String> {
        self.selector.as_ref()
    }

    /// Returns the latest value received for the specified item/field pair.
    ///
    /// It is suggested to consume real-time data by implementing and adding a proper SubscriptionListener rather than probing this method. In case of COMMAND Subscriptions, the value returned by this method may be misleading, as in COMMAND mode all the keys received, being part of the same item, will overwrite each other; for COMMAND Subscriptions, use `Subscription.getCommandValue()` instead.
    ///
    /// Note that internal data is cleared when the Subscription is unsubscribed from.
    ///
    /// # Lifecycle
    /// This method can be called at any time; if called to retrieve a value that has not been received yet, then it will return `None`.
    ///
    /// # Errors
    /// Returns an error if an invalid item name or field name is specified or if the specified item position or field position is out of bounds.
    ///
    /// # Parameters
    /// - `item_pos`: A String representing an item in the configured item list or a Number representing the 1-based position of the item in the specified item group. (In case an item list was specified, passing the item position is also possible).
    /// - `field_pos`: A String representing a field in the configured field list or a Number representing the 1-based position of the field in the specified field schema. (In case a field list was specified, passing the field position is also possible).
    ///
    /// # Returns
    /// The current value for the specified field of the specified item(possibly `None`), or `None` if no value has been received yet.
    pub fn get_value(&self, item_pos: usize, field_pos: usize) -> Option<&String> {
        self.values.get(&(item_pos, field_pos))
    }

    /// Returns the latest value received for the specified item/key/field combination in a COMMAND Subscription. This method can only be used if the Subscription mode is COMMAND. Subscriptions with two-level behavior are also supported, hence the specified field can be either a first-level or a second-level one.
    ///
    /// It is suggested to consume real-time data by implementing and adding a proper SubscriptionListener rather than probing this method.
    ///
    /// Note that internal data is cleared when the Subscription is unsubscribed from.
    ///
    /// # Lifecycle
    /// This method can be called at any time; if called to retrieve a value that has not been received yet, then it will return `None`.
    ///
    /// # Errors
    /// - Returns an error if an invalid item name or field name is specified or if the specified item position or field position is out of bounds.
    /// - Returns an error if the Subscription mode is not COMMAND.
    ///
    /// # Parameters
    /// - `item_pos`: A String representing an item in the configured item list or a Number representing the 1-based position of the item in the specified item group. (In case an item list was specified, passing the item position is also possible).
    /// - `key`: A String containing the value of a key received on the COMMAND subscription.
    /// - `field_pos`: A String representing a field in the configured field list or a Number representing the 1-based position of the field in the specified field schema. (In case a field list was specified, passing the field position is also possible).
    ///
    /// # Returns
    /// The current value for the specified field of the specified key within the specified item (possibly `None`), or `None` if the specified key has not been added yet (note that it might have been added and eventually deleted).
    pub fn get_command_value(
        &self,
        item_pos: usize,
        key: &str,
        field_pos: usize,
    ) -> Option<&String> {
        let key = format!("{}_{}", item_pos, key);
        self.command_values
            .get(&key)
            .and_then(|fields| fields.get(&field_pos))
    }

    /// Inquiry method that checks if the Subscription is currently "active" or not. Most of the Subscription properties cannot be modified if a Subscription is "active".
    ///
    /// The status of a Subscription is changed to "active" through the `LightstreamerClient.subscribe()` method and back to "inactive" through the `LightstreamerClient.unsubscribe()` one.
    ///
    /// # Lifecycle
    /// This method can be called at any time.
    ///
    /// # Returns
    /// `true`/`false` if the Subscription is "active" or not.
    ///
    /// # See also
    /// `LightstreamerClient.subscribe()`
    ///
    /// # See also
    /// `LightstreamerClient.unsubscribe()`
    pub fn is_active(&self) -> bool {
        self.is_active
    }

    /// Inquiry method that checks if the Subscription is currently subscribed to through the server or not.
    ///
    /// This flag is switched to true by server sent Subscription events, and back to false in case of client disconnection, `LightstreamerClient.unsubscribe()` calls and server sent unsubscription events.
    ///
    /// # Lifecycle
    /// This method can be called at any time.
    ///
    /// # Returns
    /// `true`/`false` if the Subscription is subscribed to through the server or not.
    pub fn is_subscribed(&self) -> bool {
        self.is_subscribed
    }

    /// Returns the position of the "key" field in a COMMAND Subscription.
    ///
    /// This method can only be used if the Subscription mode is COMMAND and the Subscription was initialized using a "Field Schema".
    ///
    /// # Lifecycle
    /// This method can be called at any time after the first `SubscriptionListener.onSubscription()` event.
    ///
    /// # Errors
    /// - Returns an error if the Subscription mode is not COMMAND or if the `SubscriptionListener.onSubscription()` event for this Subscription was not yet fired.
    /// - Returns an error if a "Field List" was specified.
    ///
    /// # Returns
    /// The 1-based position of the "key" field within the "Field Schema".
    pub fn get_key_position(&self) -> Option<usize> {
        if self.mode != SubscriptionMode::Command || !self.is_subscribed {
            return None;
        }
        if let Some(ref schema) = self.field_schema {
            return schema.split(',').position(|field| field.trim() == "key");
        }
        None
    }

    /// Returns the position of the "command" field in a COMMAND Subscription.
    ///
    /// This method can only be used if the Subscription mode is COMMAND and the Subscription was initialized using a "Field Schema".
    ///
    /// # Lifecycle
    /// This method can be called at any time after the first `SubscriptionListener.onSubscription()` event.
    ///
    /// # Errors
    /// - Returns an error if the Subscription mode is not COMMAND or if the `SubscriptionListener.onSubscription()` event for this Subscription was not yet fired.
    ///
    /// # Returns
    /// The 1-based position of the "command" field within the "Field Schema".
    pub fn get_command_position(&self) -> Option<usize> {
        if self.mode != SubscriptionMode::Command || !self.is_subscribed {
            return None;
        }
        if let Some(ref schema) = self.field_schema {
            return schema
                .split(',')
                .position(|field| field.trim() == "command");
        }
        None
    }

    /*
    /// Handles the subscription event.
    pub fn on_subscription(&mut self) {
        self.is_subscribed = true;
        for listener in &mut self.listeners {
            listener.on_subscription();
        }
    }

    /// Handles the unsubscription event.
    pub fn on_unsubscription(&mut self) {
        self.is_subscribed = false;
        self.values.clear();
        self.command_values.clear();
        for listener in &mut self.listeners {
            listener.on_unsubscription();
        }
    }

    /// Handles an update event for a regular Subscription.
    pub fn on_update(&mut self, item_pos: usize, field_pos: usize, value: String, is_snapshot: bool) {
        self.values.insert((item_pos, field_pos), value.clone());
        for listener in &mut self.listeners {
            listener.on_update(item_pos, field_pos, &value, is_snapshot);
        }
    }

    /// Handles an update event for a COMMAND Subscription.
    pub fn on_command_update(&mut self, key: String, item_pos: usize, field_pos: usize, value: String, is_snapshot: bool) {
        self.command_values
            .entry(key.clone())
            .or_insert_with(HashMap::new)
            .insert(field_pos, value.clone());
        for listener in &mut self.listeners {
            listener.on_command_update(&key, item_pos, field_pos, &value, is_snapshot);
        }
    }
    */
}

impl Debug for Subscription {
    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
        f.debug_struct("Subscription")
            .field("mode", &self.mode)
            .field("item_group", &self.item_group)
            .field("items", &self.items)
            .field("field_schema", &self.field_schema)
            .field("fields", &self.fields)
            .field("data_adapter", &self.data_adapter)
            .field(
                "command_second_level_data_adapter",
                &self.command_second_level_data_adapter,
            )
            .field(
                "command_second_level_field_schema",
                &self.command_second_level_field_schema,
            )
            .field(
                "command_second_level_fields",
                &self.command_second_level_fields,
            )
            .field("requested_buffer_size", &self.requested_buffer_size)
            .field("requested_max_frequency", &self.requested_max_frequency)
            .field("requested_snapshot", &self.requested_snapshot)
            .field("selector", &self.selector)
            .field("is_active", &self.is_active)
            .field("is_subscribed", &self.is_subscribed)
            .finish()
    }
}