ot-tools-io 0.11.2

A library crate for reading/writing binary data files used by the Elektron Octatrack DPS-1.
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
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
/*
SPDX-License-Identifier: GPL-3.0-or-later
Copyright © 2024 Mike Robeson [dijksterhuis]
*/

use crate::arrangements::ArrangeRow;
use crate::identifiers::{
    ArrId, BankId, PartId, PatternId, PlaybackSlotId, RecBufId, SavedState, SceneId, SliceId,
    TrackId, TrigId,
};
use crate::macros::*;
use crate::markers::SlotMarkers;
use crate::parts::Part;
use crate::patterns::Pattern;
use crate::projects::SlotAttributes;
use crate::{
    ArrangementFile, BankFile, Defaults, HasHeaderField, OctatrackFileIO, OtToolsIoError,
    SampleSettingsFile,
};
use serde::{Deserialize, Deserializer, Serialize, Serializer};
use serde_big_array::BigArray;
use std::array::from_fn;
use std::ops::{Deref, DerefMut, Index, IndexMut};
use std::path::PathBuf;

/// Generic collection for [`ArrangementFile`]s.
///
/// # [`Serialize`]/[`Deserialize`]
///
/// Neither [`Serialize`] nor [`Deserialize`] are implemented for this type.
///
/// # `Box` (no `Copy`)
///
/// The inner array of this type is wrapped in a `Box`.
/// -- we cannot fit all [`ArrangementFile`]s on the stack.
/// Unfortunately this means the type does not implement `Copy`.
///
/// # Example: Extending in your own code with custom inner types
/// ```
/// use std::path::PathBuf;
/// use ot_tools_io::types::Arrangements;
///
/// use ot_tools_io::Defaults;
/// use ot_tools_io_derive::{ArrayDefaults, BoxedArrayDefaults};
/// use std::array::from_fn;
///
/// #[derive(Debug, PartialEq, Default, ArrayDefaults, BoxedArrayDefaults)]
/// pub struct BackupPath(PathBuf);
///
/// # fn main() -> Result<(), ()> {
/// let mut my_backups = Arrangements::<BackupPath>::default();
/// let my_new_backup = BackupPath(PathBuf::from("some_path"));
/// let first = my_backups.first_mut().ok_or(())?;
/// *first = my_new_backup;
///
/// // first one changed
/// assert_eq!(my_backups[0], BackupPath(PathBuf::from("some_path")));
/// // rest are default
/// assert_eq!(my_backups[1], BackupPath::default());
///
/// // correct length
/// assert_eq!(my_backups.len(), 8);
///
/// # Ok(()) }
/// ```
#[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub struct Arrangements<T>(Box<[T; 8]>);

impl<T> Arrangements<T> {
    pub fn new(value: [T; 8]) -> Self {
        Self(Box::new(value))
    }

    pub fn new_boxed(value: Box<[T; 8]>) -> Self {
        Self(value)
    }
}

generic_newtype_id_lookups!(Arrangements, ArrId);
generic_newtype_unbox!(Arrangements, 8);
generic_newtype_asref!(Arrangements);
generic_newtype_asmut!(Arrangements);
generic_newtype_deref!(Arrangements, 8);
generic_newtype_deref_mut!(Arrangements);

impl<T: Defaults<Box<[T; 8]>> + Default> Default for Arrangements<T> {
    fn default() -> Self {
        Self(T::defaults())
    }
}

impl HasHeaderField for Arrangements<ArrangementFile> {
    fn check_header(&self) -> Result<bool, OtToolsIoError> {
        Ok(self.iter().all(|x| x.check_header().is_ok_and(|x| x)))
    }
}

/// Concrete implementation for [`ArrangementFile`] adds two methods for reading and writing a
/// batch of files.
impl Arrangements<ArrangementFile> {
    /// Reads a collection of [`ArrangementFile`]s from a directory.
    pub fn from_data_files<P>(dirpath: P, state: &SavedState) -> Result<Self, OtToolsIoError>
    where
        PathBuf: From<P>,
    {
        let mut new = Self::default();
        let path = PathBuf::from(dirpath);
        for id in ArrId::iter() {
            let data = ArrangementFile::from_data_file(&path.join(id.file_stem(state)))?;
            new[id.as_index()] = data;
        }
        Ok(new)
    }

    /// Writes a collection of [`ArrangementFile`]s to a directory.
    ///
    /// Will skip writing a particular [`ArrangementFile`] if the
    /// `skip_unchanged` argument is `true` and the current [`ArrangementFile`]
    /// matches the data in the existing file on the file system.
    pub fn to_data_files<P>(
        &self,
        dirpath: P,
        state: &SavedState,
        skip_unchanged: bool,
    ) -> Result<(), OtToolsIoError>
    where
        PathBuf: From<P>,
    {
        let path = PathBuf::from(dirpath);
        for id in ArrId::iter() {
            let arr = self.id_ref(&id);
            if skip_unchanged {
                if let Ok(exists) = ArrangementFile::from_data_file(&path.join(id.file_stem(state)))
                {
                    if &exists != arr {
                        arr.to_data_file(&path.join(id.file_stem(state)))?;
                    }
                } else {
                    // probably doesn't exist
                    arr.to_data_file(&path.join(id.file_stem(state)))?;
                }
            } else {
                arr.to_data_file(&path.join(id.file_stem(state)))?;
            }
        }
        Ok(())
    }
}

/// Generic array wrapper for [`ArrangeRow`]s.
///
/// # Example: Extending in your own code with custom inner types
/// ```
/// use ot_tools_io::types::ArrangeRows;
///
/// use ot_tools_io::Defaults;
/// use ot_tools_io_derive::{ArrayDefaults, BoxedArrayDefaults};
/// use std::array::from_fn;
///
/// #[derive(Debug, PartialEq, Default, ArrayDefaults, BoxedArrayDefaults)]
/// pub struct CustomReminder(String);
///
/// # fn main() -> Result<(), ()> {
/// let mut my_arr_reminders = ArrangeRows::<CustomReminder>::default();
/// let first = my_arr_reminders.first_mut().ok_or(())?;
/// *first = CustomReminder(
///     String::from(
///         "imagine this is a long reminder value that goes on for longer than normally allowed"
///     )
/// );
///
/// // first one changed
/// assert_eq!(
///     my_arr_reminders[0],
///     CustomReminder(
///         String::from(
///             "imagine this is a long reminder value that goes on for longer than normally allowed"
///         )
///     )
/// );
/// // rest are default
/// assert_eq!(my_arr_reminders[1], CustomReminder::default());
///
/// // correct length
/// assert_eq!(my_arr_reminders.len(), 256);
///
/// # Ok(()) }
/// ```
#[derive(Copy, Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub struct ArrangeRows<T>([T; 256]);

impl<T> ArrangeRows<T> {
    pub fn new(value: [T; 256]) -> Self {
        Self(value)
    }
}

generic_newtype_asref!(ArrangeRows);
generic_newtype_asmut!(ArrangeRows);
generic_newtype_deref!(ArrangeRows, 256);
generic_newtype_deref_mut!(ArrangeRows);

impl<T: Defaults<[T; 256]> + Default> Default for ArrangeRows<T> {
    fn default() -> Self {
        Self(T::defaults())
    }
}

impl<'de> Deserialize<'de> for ArrangeRows<ArrangeRow> {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        Ok(Self(
            <[ArrangeRow; 256] as BigArray<ArrangeRow>>::deserialize(deserializer)?,
        ))
    }
}

impl Serialize for ArrangeRows<ArrangeRow> {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        <[ArrangeRow; 256] as BigArray<ArrangeRow>>::serialize(&self.0, serializer)
    }
}

/// Generic collection for [`BankFile`]s.
///
/// # [`Serialize`]/[`Deserialize`]
///
/// Neither [`Serialize`] nor [`Deserialize`] are implemented for this type.
///
/// # `Box` (no `Copy`)
///
/// The inner array of this type is wrapped in a `Box`.
/// -- we cannot fit all [`BankFile`]s on the stack.
/// Unfortunately this means the type does not implement `Copy`.
///
/// # Example: Extending in your own code with custom inner types
/// ```
/// use ot_tools_io::types::Banks;
/// use std::path::PathBuf;
///
/// use ot_tools_io::Defaults;
/// use ot_tools_io_derive::{ArrayDefaults, BoxedArrayDefaults};
/// use std::array::from_fn;
///
/// #[derive(Debug, PartialEq, Default, ArrayDefaults, BoxedArrayDefaults)]
/// pub struct YamlPath(PathBuf);
///
/// # fn main() -> Result<(), ()> {
/// let mut my_bank_yamls = Banks::<YamlPath>::default();
/// let first = my_bank_yamls.first_mut().ok_or(())?;
/// *first = YamlPath(PathBuf::from("some_path"));
///
/// // first one changed
/// assert_eq!(my_bank_yamls[0], YamlPath(PathBuf::from("some_path")));
/// // rest are default
/// assert_eq!(my_bank_yamls[1], YamlPath::default());
///
/// // correct length
/// assert_eq!(my_bank_yamls.len(), 16);
///
/// # Ok(()) }
/// ```
#[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub struct Banks<T>(Box<[T; 16]>);

impl<T> Banks<T> {
    pub fn new(value: [T; 16]) -> Self {
        Self(Box::new(value))
    }

    pub fn new_boxed(value: Box<[T; 16]>) -> Self {
        Self(value)
    }
}

generic_newtype_id_lookups!(Banks, BankId);
generic_newtype_unbox!(Banks, 16);
generic_newtype_asref!(Banks);
generic_newtype_asmut!(Banks);
generic_newtype_deref!(Banks, 16);
generic_newtype_deref_mut!(Banks);

impl<T: Defaults<Box<[T; 16]>> + Default> Default for Banks<T> {
    fn default() -> Self {
        Self(T::defaults())
    }
}

impl HasHeaderField for Banks<BankFile> {
    fn check_header(&self) -> Result<bool, OtToolsIoError> {
        Ok(self.iter().all(|x| x.check_header().is_ok_and(|x| x)))
    }
}

/// Concrete implementation for [`BankFile`]s.
/// Implements methods for reading and writing all [`BankFile`]s within an octatrack project directory.
impl Banks<BankFile> {
    /// Reads a collection of [`BankFile`]s from a directory.
    pub fn from_data_files<P>(dirpath: P, state: &SavedState) -> Result<Self, OtToolsIoError>
    where
        PathBuf: From<P>,
    {
        let mut new = Self::default();
        let path = PathBuf::from(dirpath);
        for id in BankId::iter() {
            let bank = BankFile::from_data_file(&path.join(id.file_stem(state)))?;
            new[id.as_index()] = bank;
        }
        Ok(new)
    }

    /// Writes a collection of [`BankFile`]s to a directory
    ///
    /// Will skip writing a particular [`BankFile`] if the `skip_unchanged`
    /// argument is `true` and the current [`BankFile`] matches the data in the
    /// existing file on the file system.
    pub fn to_data_files<P>(
        &self,
        dirpath: P,
        state: &SavedState,
        skip_unchanged: bool,
    ) -> Result<(), OtToolsIoError>
    where
        PathBuf: From<P>,
    {
        let path = PathBuf::from(dirpath);
        for id in BankId::iter() {
            let bank = self.id_ref(&id);
            if skip_unchanged {
                if let Ok(exists) = BankFile::from_data_file(&path.join(id.file_stem(state))) {
                    if &exists != bank {
                        bank.to_data_file(&path.join(id.file_stem(state)))?;
                    }
                } else {
                    // probably doesn't exist
                    bank.to_data_file(&path.join(id.file_stem(state)))?;
                }
            } else {
                bank.to_data_file(&path.join(id.file_stem(state)))?;
            }
        }
        Ok(())
    }
}

/// Generic collection for [`Part`]s
///
/// # [`Serialize`]/[`Deserialize`]
///
/// [`Serialize`] and [`Deserialize`] are implemented for this type.
///
/// # `Box` (no `Copy`)
///
/// The inner array of this type is wrapped in a `Box`.
/// Fields within a [`Part`] already use a `Box` so we are forced to wrap the data in a `Box` here.
///
/// # Example: Extending in your own code with custom inner types
/// ```
/// use ot_tools_io::types::Parts;
/// use std::path::PathBuf;
///
/// use ot_tools_io::Defaults;
/// use ot_tools_io_derive::{ArrayDefaults, BoxedArrayDefaults};
/// use std::array::from_fn;
///
/// #[derive(Debug, PartialEq, Default, ArrayDefaults, BoxedArrayDefaults)]
/// pub struct LongPartName(String);
///
/// # fn main() -> Result<(), ()> {
/// let mut my_part_names = Parts::<LongPartName>::default();
/// let first = my_part_names.first_mut().ok_or(())?;
/// *first = LongPartName(String::from("My awesome part name that is too long on the octatrack"));
///
/// // first one changed
/// assert_eq!(
///     my_part_names[0],
///     LongPartName(
///         String::from("My awesome part name that is too long on the octatrack")
///     )
/// );
/// // rest are default
/// assert_eq!(my_part_names[1], LongPartName::default());
///
///
/// // correct length
/// assert_eq!(my_part_names.len(), 4);
///
/// # Ok(()) }
/// ```
#[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub struct Parts<T>(Box<[T; 4]>);

impl<T> Parts<T> {
    pub fn new(value: [T; 4]) -> Self {
        Self(Box::new(value))
    }

    pub fn new_boxed(value: Box<[T; 4]>) -> Self {
        Self(value)
    }
}

generic_newtype_id_lookups!(Parts, PartId);
generic_newtype_unbox!(Parts, 4);
generic_newtype_asref!(Parts);
generic_newtype_asmut!(Parts);
generic_newtype_deref!(Parts, 4);
generic_newtype_deref_mut!(Parts);

impl<T: Defaults<Box<[T; 4]>> + Default> Default for Parts<T> {
    fn default() -> Self {
        Self(T::defaults())
    }
}

impl<'de> Deserialize<'de> for Parts<Part> {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        let boxed = Box::new(<[Part; 4] as BigArray<Part>>::deserialize(deserializer)?);
        Ok(Self(boxed))
    }
}

impl Serialize for Parts<Part> {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        <[Part; 4] as BigArray<Part>>::serialize(&self.0, serializer)
    }
}

impl HasHeaderField for Parts<Part> {
    fn check_header(&self) -> Result<bool, OtToolsIoError> {
        Ok(self.iter().all(|x| x.check_header().is_ok_and(|x| x)))
    }
}

/// Generic collection for [`Pattern`]s
///
/// # [`Serialize`]/[`Deserialize`]
///
/// [`Serialize`] and [`Deserialize`] are implemented for this type.
///
/// # `Box` (no `Copy`)
///
/// Unfortunately serde requires that we wrap the inner array of `Patterns` in a `Box`.
/// So `Patterns`, and any type that contains a `Patterns` type, cannot implement the `Copy`
/// trait.
///
/// # Example: Extending in your own code with custom inner types
/// ```
/// use ot_tools_io::types::Patterns;
/// use std::path::PathBuf;
///
/// use ot_tools_io::Defaults;
/// use ot_tools_io_derive::{ArrayDefaults, BoxedArrayDefaults};
/// use std::array::from_fn;
///
/// #[derive(Debug, PartialEq, Default, ArrayDefaults, BoxedArrayDefaults)]
/// pub struct SomeString(String);
///
/// # fn main() -> Result<(), ()> {
/// let mut my_pattern_descriptions = Patterns::<SomeString>::default();
/// let first = my_pattern_descriptions.first_mut().ok_or(())?;
/// *first = SomeString(String::from("My awesome pattern"));
///
/// // first one changed
/// assert_eq!(
///     my_pattern_descriptions[0],
///     SomeString(
///         String::from("My awesome pattern")
///     )
/// );
/// // rest are default
/// assert_eq!(my_pattern_descriptions[1], SomeString::default());
///
/// // correct length
/// assert_eq!(my_pattern_descriptions.len(), 16);
///
/// # Ok(()) }
/// ```
#[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub struct Patterns<T>(Box<[T; 16]>);

impl<T> Patterns<T> {
    pub fn new(value: [T; 16]) -> Self {
        Self(Box::new(value))
    }

    pub fn new_boxed(value: Box<[T; 16]>) -> Self {
        Self(value)
    }
}

generic_newtype_id_lookups!(Patterns, PatternId);
generic_newtype_unbox!(Patterns, 16);
generic_newtype_asref!(Patterns);
generic_newtype_asmut!(Patterns);
generic_newtype_deref!(Patterns, 16);
generic_newtype_deref_mut!(Patterns);

impl<T: Defaults<Box<[T; 16]>> + Default> Default for Patterns<T> {
    fn default() -> Self {
        Self(T::defaults())
    }
}

impl<'de> Deserialize<'de> for Patterns<Pattern> {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        let boxed = Box::new(<[Pattern; 16] as BigArray<Pattern>>::deserialize(
            deserializer,
        )?);
        Ok(Self(boxed))
    }
}

impl Serialize for Patterns<Pattern> {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        <[Pattern; 16] as BigArray<Pattern>>::serialize(&self.0, serializer)
    }
}

impl HasHeaderField for Patterns<Pattern> {
    fn check_header(&self) -> Result<bool, OtToolsIoError> {
        Ok(self.iter().all(|x| x.check_header().is_ok_and(|x| x)))
    }
}

/// Generic collection for data related to tracks, e.g. for Recording Buffers, Audio Track Trigs,
/// MIDI Track Trigs and the like.
/// Used by a lot of fields on the [`Part`] and [`Pattern`] types.
///
/// # `Copy` (no `Box`)
///
/// This generic collection helper does not use `Box` and can be `Copy`.
///
/// # Example: Using in your own code with custom inner types
///
/// ```
/// use ot_tools_io::types::Tracks;
/// use ot_tools_io::Defaults;
/// use ot_tools_io_derive::ArrayDefaults;
/// use std::array::from_fn;
///
/// #[derive(Debug, PartialEq, Default, ArrayDefaults)]
/// pub struct SomeNumber(u8);
///
/// fn main() -> Result<(), ()> {
///     let mut my_tracks = Tracks::<SomeNumber>::default();
///     let first = my_tracks.first_mut().ok_or(())?;
///     *first = SomeNumber(100);
///
///     // first one changed
///     assert_eq!(my_tracks[0], SomeNumber(100));
///     // rest are default
///     assert_eq!(my_tracks[1], SomeNumber(0));
///
///     // correct length
///     assert_eq!(my_tracks.len(), 8);
///
///     Ok(())
/// }
/// ```
#[derive(Copy, Clone, Debug, Eq, PartialEq, Ord, PartialOrd, Hash)]
pub struct Tracks<T>([T; 8]);

generic_newtype_id_lookups!(Tracks, TrackId);
generic_newtype_asref!(Tracks);
generic_newtype_asmut!(Tracks);
generic_newtype_deref!(Tracks, 8);
generic_newtype_deref_mut!(Tracks);
generic_newtype_index!(Tracks);
generic_newtype_index_mut!(Tracks);

impl<T: Defaults<[T; 8]> + Default> Default for Tracks<T> {
    fn default() -> Self {
        Self(T::defaults())
    }
}

impl<const N: usize, T: Default> Defaults<[Self; N]> for Tracks<T> {
    fn defaults() -> [Self; N]
    where
        Self: Default,
    {
        from_fn(|_| Self::default())
    }
}

impl<T> Tracks<T> {
    pub fn new(value: [T; 8]) -> Self {
        Self(value)
    }
}

impl<'de, T: Deserialize<'de>> Deserialize<'de> for Tracks<T> {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        Ok(Self(<[T; 8] as BigArray<T>>::deserialize(deserializer)?))
    }
}

impl<T: Serialize> Serialize for Tracks<T> {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        <[T; 8] as BigArray<T>>::serialize(&self.0, serializer)
    }
}

/// Generic collection for scene data.
/// Used in the `scenes` and `scene_xlvs` fields on [`Part`].
///
/// # `Copy` (no `Box`)
///
/// This generic collection helper does not use `Box` and can be `Copy`.
///
/// # Example: Using in your own code with custom inner types
///
/// ```
/// use ot_tools_io::types::Scenes;
/// use ot_tools_io::Defaults;
/// use ot_tools_io_derive::ArrayDefaults;
/// use std::array::from_fn;
///
/// #[derive(Debug, PartialEq, Default, ArrayDefaults)]
/// pub struct SomeNumber(u8);
///
/// fn main() -> Result<(), ()> {
///     let mut my_scenes = Scenes::<SomeNumber>::default();
///     let first = my_scenes.first_mut().ok_or(())?;
///     *first = SomeNumber(100);
///
///     // first one changed
///     assert_eq!(my_scenes[0], SomeNumber(100));
///     // rest are default
///     assert_eq!(my_scenes[1], SomeNumber(0));
///
///     // correct length
///     assert_eq!(my_scenes.len(), 16);
///
///     Ok(())
/// }
/// ```
#[derive(Copy, Clone, Debug, Eq, PartialEq, Ord, PartialOrd, Hash)]
pub struct Scenes<T>([T; 16]);

generic_newtype_id_lookups!(Scenes, SceneId);
generic_newtype_asref!(Scenes);
generic_newtype_asmut!(Scenes);
generic_newtype_deref!(Scenes, 16);
generic_newtype_deref_mut!(Scenes);
generic_newtype_index!(Scenes);
generic_newtype_index_mut!(Scenes);

impl<T: Defaults<[T; 16]> + Default> Default for Scenes<T> {
    fn default() -> Self {
        Self(T::defaults())
    }
}

impl<T> Scenes<T> {
    pub fn new(value: [T; 16]) -> Self {
        Self(value)
    }
}

impl<'de, T: Deserialize<'de>> Deserialize<'de> for Scenes<T> {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        Ok(Self(<[T; 16] as BigArray<T>>::deserialize(deserializer)?))
    }
}

impl<T: Serialize> Serialize for Scenes<T> {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        <[T; 16] as BigArray<T>>::serialize(&self.0, serializer)
    }
}

/// Generic collection for slice data.
///
/// # Example: Using in your own code with custom inner types
///
/// ```
/// use ot_tools_io::types::Slices;
/// use ot_tools_io::Defaults;
/// use ot_tools_io_derive::ArrayDefaults;
/// use std::array::from_fn;
///
/// #[derive(Debug, PartialEq, Default, ArrayDefaults)]
/// pub struct SomeNumber(u8);
///
/// fn main() -> Result<(), ()> {
///     let mut my_slices = Slices::<SomeNumber>::default();
///     let first = my_slices.first_mut().ok_or(())?;
///     *first = SomeNumber(100);
///
///     // first one changed
///     assert_eq!(my_slices[0], SomeNumber(100));
///     // rest are default
///     assert_eq!(my_slices[1], SomeNumber(0));
///
///     // correct length
///     assert_eq!(my_slices.len(), 64);
///
///     Ok(())
/// }
/// ```
#[derive(Copy, Clone, Debug, Eq, PartialEq, Ord, PartialOrd, Hash)]
pub struct Slices<T>([T; 64]);

generic_newtype_id_lookups!(Slices, SliceId);
generic_newtype_asref!(Slices);
generic_newtype_asmut!(Slices);
generic_newtype_deref!(Slices, 64);
generic_newtype_deref_mut!(Slices);
generic_newtype_index!(Slices);
generic_newtype_index_mut!(Slices);
generic_newtype_into_iter!(Slices, 64);

impl<T: Defaults<[T; 64]> + Default> Default for Slices<T> {
    fn default() -> Self {
        Self(T::defaults())
    }
}

impl<T> Slices<T> {
    pub fn new(value: [T; 64]) -> Self {
        Self(value)
    }
}

impl<'de, T: Deserialize<'de>> Deserialize<'de> for Slices<T> {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        Ok(Self(<[T; 64] as BigArray<T>>::deserialize(deserializer)?))
    }
}

impl<T: Serialize> Serialize for Slices<T> {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        <[T; 64] as BigArray<T>>::serialize(&self.0, serializer)
    }
}

/// Generic collection for data related to trigs.
/// Used in [`Pattern`]s with parameter lock trig assignments and trig offset/repeat/conditions data.
///
/// # `Box` (no-`Copy`)
///
/// Unfortunately serde requires that we wrap the inner array type of [`Trigs`] in a `Box`.
/// As a result, [`Trigs`] and any type that contains a [`Trigs`] type cannot implement the `Copy` trait.
///
/// # Example: Using in your own code with custom inner types
///
/// ```
/// use ot_tools_io::types::Trigs;
/// use ot_tools_io::Defaults;
/// use ot_tools_io_derive::{ArrayDefaults, BoxedArrayDefaults};
/// use std::array::from_fn;
///
/// #[derive(Debug, PartialEq, Default, ArrayDefaults, BoxedArrayDefaults)]
/// pub struct SomeNumber(u8);
///
/// fn main() -> Result<(), ()> {
///     let mut my_trigs = Trigs::<SomeNumber>::default();
///     let first = my_trigs.first_mut().ok_or(())?;
///     *first = SomeNumber(100);
///
///     // first one changed
///     assert_eq!(my_trigs[0], SomeNumber(100));
///     // rest are default
///     assert_eq!(my_trigs[1], SomeNumber(0));
///
///     // correct length
///     assert_eq!(my_trigs.len(), 64);
///
///     Ok(())
/// }
/// ```
#[derive(Clone, Debug, Eq, PartialEq, Ord, PartialOrd, Hash)]
pub struct Trigs<T>(Box<[T; 64]>);

generic_newtype_id_lookups!(Trigs, TrigId);
generic_newtype_unbox!(Trigs, 64);
generic_newtype_asref!(Trigs);
generic_newtype_asmut!(Trigs);
generic_newtype_deref!(Trigs, 64);
generic_newtype_deref_mut!(Trigs);

impl<T: Defaults<Box<[T; 64]>> + Default> Default for Trigs<T> {
    fn default() -> Self {
        Self(T::defaults())
    }
}

impl<T> Trigs<T> {
    pub fn new(value: [T; 64]) -> Self {
        Self(Box::new(value))
    }

    pub fn new_boxed(value: Box<[T; 64]>) -> Self {
        Self(value)
    }
}

impl<'de, T: Deserialize<'de>> Deserialize<'de> for Trigs<T> {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        Ok(Self(Box::new(<[T; 64] as BigArray<T>>::deserialize(
            deserializer,
        )?)))
    }
}

impl<T: Serialize> Serialize for Trigs<T> {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        <[T; 64] as BigArray<T>>::serialize(&self.0, serializer)
    }
}

impl<T, I> Index<I> for Trigs<T>
where
    [T]: Index<I>,
{
    type Output = <[T] as Index<I>>::Output;
    #[inline]
    fn index(&self, index: I) -> &Self::Output {
        Index::index(&*self.0 as &[T], index)
    }
}

impl<T, I> IndexMut<I> for Trigs<T>
where
    [T]: IndexMut<I>,
{
    #[inline]
    fn index_mut(&mut self, index: I) -> &mut Self::Output {
        IndexMut::index_mut(&mut *self.0 as &mut [T], index)
    }
}

#[allow(rustdoc::invalid_rust_codeblocks)]
/// Generic collection for **playback slot** items, e.g. Static and Flex slot data.
///
/// # Extending: Custom New Types
///
/// As this type is generic you can use custom new type structs in downstream applications /
/// libraries, e.g. to use your own custom 'ApplicationSlot' type which has extra methods/fields.
///
/// ```
/// use ot_tools_io::types::PlaybackSlots;
/// use ot_tools_io::Defaults;
/// use std::path::PathBuf;
///
/// #[derive(Debug, PartialEq)]
/// pub struct PathOnlySlotType(PathBuf);
///
/// impl Default for PathOnlySlotType {
///     fn default() -> Self {
///         Self(PathBuf::from("default/path/to/some/file.ext"))
///     }
/// }
///
/// impl Defaults<Box<[Self; 128]>> for PathOnlySlotType {
///     fn defaults() -> Box<[Self; 128]> where Self: Default {
///         Box::new(std::array::from_fn(|_| Self::default()))
///     }
/// }
///
/// # fn main() -> Result<(), ()> {
/// let mut my_slots = PlaybackSlots::<PathOnlySlotType>::default();
/// let first = my_slots.first_mut().ok_or(())?;
/// *first = PathOnlySlotType(PathBuf::from("some_path"));
///
/// // first one changed
/// assert_eq!(my_slots[0], PathOnlySlotType(PathBuf::from("some_path")));
/// // rest are default
/// assert_eq!(my_slots[1], PathOnlySlotType::default());
/// # Ok(()) }
/// ```
///
/// # Note: Name of the type
///
/// This type should only hold elements related to static or flex slots.
/// i.e. no recording buffer slots, ever (slot_type = flex, slot_id > 128 etc.).
///
/// Admittedly the name [`PlaybackSlots`] is somewhat of a misnomer
/// - Flex slots can be recorded to
/// - Sample data stored in Recording Buffers can be played back on audio tracks
///
/// However, those are *special cases* of Octatrack usage:
/// - The designed intent of Recording Buffers is to **record to the slot**.
/// - The designed intent of Flex Slots is to **edit the audio data and playback**.
/// - The designed intent of Static Slots is to **only playback**.
///
/// # Explainer: Why does this type exist?
///
/// > **note**: the examples in this section may not compile.
/// > they are here to demonstrate problems when using previous versions of slot data types.
/// > they are not here as examples to actually implement yourself!
///
/// Recording Buffers are Flex slots with a Slot ID > 128 under the hood (or more literally the
/// metal case) of the Octatrack.
/// I originally decided to represent this in this "io" library.
/// Recording buffers are actually Flex slots.
/// That was it.
/// Done.
///
/// The point of the library was to load data from the binary files at the lowest granularity
/// possible
/// -- representing how data is stored in each binary file.
/// The thinking behind this decision was that it would allow more flexibility when using the
/// library
/// -- access to data at the lowest granularity means the ability to do "more stuff", right?
///
/// Having worked with the data in that format for a while
/// -- it is a massive pain in the arse dealing with the "recording buffers are actually flex slots"
/// special case.
///
/// The library now treats Recording Buffers as a different special type of slot during
/// Serialization/Deserialization
/// -- separate to Flex and Static slots which are considered **Playback Slots**.
///
/// ## first example of the pain
/// - simple matches need an extra case where you need to be aware of the `slot_id > 128` rule.
/// - users needing to be aware of some hidden logic/rule == bad.
/// - my first draft of this example got the rule wrong! i used `slot_id > 129`! and i'm the author
///   of this library!
/// ```compile_fail
/// match slot.slot_type {
///     SlotType::Static => {}, // do something to static slots
///     SlotType::Flex => {}, // do something to flex slots
///     SlotType::Flex if slot.slot_id > 128 => _, // this one
/// }
/// ```
/// ## second example of the pain
/// - our `flex_slots` variable contains `Option<SlotAttributes>` instances with the `slot_type` field
///   equal to `SlotType::Flex` -- so, only flex slot data, right?
/// - not necessarily ... we often still need to check whether an element returned from the
///   collection is actually a flex playback slot and not a recording buffer slot.
/// - so we have to doa manual check on the `slot_id` field
/// - again, users needing to be aware of some hidden logic/rule == bad.
/// ```compile_fail
/// // (note: rust 2024 required for let chains)
/// let flex_slot_maybe = flex_slots
///     .get(some_index)
///     .map(|x| {
///         if let Some(slot_attrs) = x
///             && slot_attrs.slot_type == SlotType::Flex
///             && slot_attrs.slot_id <= 128 // our "ignore recording buffers" rule
///             { Some(possible_flex_slot) }
///         } else {
///             None
///         }
///     });
///
/// let actual_flex_slot = flex_slot_maybe.ok_or(SomeErr)?;
/// ```
///
/// ## third example of the pain
/// - can't do this with raw data -- the underlying arrays are different sizes so they are different
///   types!
/// - [`as_array`](https://doc.rust-lang.org/std/primitive.slice.html#method.as_array) will return
///   `None` for our flex slots!
///
/// > `pub const fn as_array<const N: usize>(&self) -> Option<&[T; N]>`
///
/// > If `N` is not exactly equal to the length of `self`, then this method returns `None`.
/// ```compile_fail
/// fn get_slot_attrs_by_type(
///     project_file: &ProjectFile,
///     slot_type: SlotType,
/// ) -> Option<&[Option<SlotAttributes>; 128]> {
///     match slot_type {
///         SlotType::Static => project_file.slots.static_slots.as_array(),
///         SlotType::Flex => project_file.slots.flex_slots.as_array(),
///     }
/// }
///
/// // always `None` due to the size issue
/// assert_eq!(get_slot_attrs_for_type(&file, SlotType::Flex), None)
/// ```
/// ## possible solutions to the pain?
///
/// one possible solution is making `get_slot_attrs_by_type` accept a generic size argument ...
/// ```compile_fail
/// fn get_slot_attrs_by_type<const N: usize>(
///     project_file: &ProjectFile,
///     slot_type: SlotType,
/// ) -> &[Option<SlotAttributes>; N];
/// ```
///
/// ... but this creates additional problems downstream
/// -- you need to create different types for different slot types with different lengths.
/// you then end up having to recreate this library's "Slots" array/collection data type(s) for your
/// own library and maintain them!
/// not ideal for a library!
/// our types are supposed to be re-usable!
///
/// another solution is just to give up!
/// stick everything in a `Vec` with cloned data!
/// forget references to arrays in the original file!
/// ... right?
///
/// ```compile_fail
/// fn get_slot_attrs_by_type(
///     project_file: &ProjectFile,
///     slot_type: SlotType,
/// ) -> Vec<Option<SlotAttributes>> {
///     let mut slots = vec![];
///
///     match slot_type {
///         SlotType::Static => for slot in project_file.slots.static_slots { slots.push(slot.clone()) },
///         SlotType::Flex => for slot in project_file.slots.flex_slots { slots.push(slot.clone()) },
///     };
///
///     slots
/// }
/// ```
///
/// but this means we can add more than 128 (or 136) slots to the `Vec` ...
/// either we check each time we push to this `Vec` that we haven't exceeded the size limit
/// (we're manually tracking size again!)
/// or we make this function generic -- which means tracking size in types downstream again!
/// oh, and because we have to `clone()` to escape the shared reference
/// -- we can have multiple owned versions of slots data which we can modify independently of each
/// other!
///
/// great!
/// now we can absolutely and completely bork someone's project files for sure!
///
/// ## the real solution to the pain
///
/// split recording buffers out separately with a different type -- [`RecordingBufferSlots<T>`] --
/// when we parse [`ProjectFile`][pf]s ...
///
/// so that's what happens now.
/// See the [`Slots<T>`] for more information.
///
/// [pf]: crate::types::ProjectFile
#[derive(Clone, PartialEq, Debug, Hash, PartialOrd, Ord, Eq)]
pub struct PlaybackSlots<T>(Box<[T; 128]>);

generic_newtype_id_lookups!(PlaybackSlots, PlaybackSlotId);
generic_newtype_asref!(PlaybackSlots);
generic_newtype_asmut!(PlaybackSlots);
generic_newtype_deref!(PlaybackSlots, 128);
generic_newtype_deref_mut!(PlaybackSlots);

impl<T: Defaults<Box<[T; 128]>> + Default> Default for PlaybackSlots<T> {
    fn default() -> Self {
        Self(T::defaults())
    }
}

impl<T> PlaybackSlots<T> {
    pub fn new(value: [T; 128]) -> Self {
        Self(Box::new(value))
    }

    pub fn new_boxed(value: Box<[T; 128]>) -> Self {
        Self(value)
    }
}

impl PlaybackSlots<Option<ActiveSlot<SlotAttributes, SlotMarkers>>> {
    /// Insert or replace the slot in the collection based on the `slot_id` field  in the provided
    /// [`ActiveSlot<SlotAttributes, SlotMarkers>`] instance.
    /// Will return
    /// - the element of the [`PlaybackSlots`] which is replaced
    /// - `None` if the slot is inserted into an empty slot
    /// - `None` if the `slot_id` field value is invalid
    pub fn insert_or_replace_by_slot_id_field(
        &mut self,
        value: ActiveSlot<SlotAttributes, SlotMarkers>,
    ) -> Option<ActiveSlot<SlotAttributes, SlotMarkers>> {
        if let Some(slot_id) = PlaybackSlotId::from_id(value.attrs_ref().slot_id) {
            let to_replace = self.id_mut(&slot_id);
            let old = to_replace.clone();
            *to_replace = Some(value);
            old
        } else {
            None
        }
    }

    pub fn take_by_id(
        &mut self,
        id: &PlaybackSlotId,
    ) -> Option<ActiveSlot<SlotAttributes, SlotMarkers>> {
        if let Some(slot) = self.get_mut(id.as_index()) {
            slot.take()
        } else {
            None
        }
    }
}

impl Default for PlaybackSlots<Option<ActiveSlot<SlotAttributes, SlotMarkers>>> {
    fn default() -> Self {
        Self(Box::new(from_fn(|_| None)))
    }
}

impl<'de, T: Deserialize<'de>> Deserialize<'de> for PlaybackSlots<T> {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        Ok(Self(Box::new(<[T; 128] as BigArray<T>>::deserialize(
            deserializer,
        )?)))
    }
}

impl<T: Serialize> Serialize for PlaybackSlots<T> {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        <[T; 128] as BigArray<T>>::serialize(&self.0, serializer)
    }
}

/// Generic collection for data related to Recording Buffers.
/// Used in the [`Slots`] type.
///
/// Recording buffers are always 8x slots -- we could re-use the [`Tracks`] generic collection
/// type instead of creating a special case, but it feels strange to me to use [`TrackId`]
/// to access slot data.
///
/// It is simple enough to convert from a [`TrackId`] to a [`RecBufId`]
/// ```
/// use ot_tools_io::identifiers::{TrackId, RecBufId};
/// # use ot_tools_io::OtToolsIoError;
/// # fn main() -> Result<(), OtToolsIoError> {
/// RecBufId::try_from(TrackId::One as u8)?;
/// # Ok(()) }
/// ```
///
/// # `Copy` (no `Box`)
///
/// This generic collection helper does not use `Box` and can be `Copy`.
///
/// # Example: Using in your own code with custom inner types
///
/// ```
/// use ot_tools_io::types::RecordingBufferSlots;
/// use ot_tools_io::Defaults;
/// use ot_tools_io_derive::ArrayDefaults;
/// use std::array::from_fn;
///
/// #[derive(Debug, PartialEq, Default, ArrayDefaults)]
/// pub struct SomeNumber(u8);
///
/// fn main() -> Result<(), ()> {
///     let mut my_recbufs = RecordingBufferSlots::<SomeNumber>::default();
///     let first = my_recbufs.first_mut().ok_or(())?;
///     *first = SomeNumber(100);
///
///     // first one changed
///     assert_eq!(my_recbufs[0], SomeNumber(100));
///     // rest are default
///     assert_eq!(my_recbufs[1], SomeNumber(0));
///
///     // correct length
///     assert_eq!(my_recbufs.len(), 8);
///
///     Ok(())
/// }
/// ```
#[derive(Copy, Clone, Debug, Eq, PartialEq, Ord, PartialOrd, Hash)]
pub struct RecordingBufferSlots<T>([T; 8]);

generic_newtype_id_lookups!(RecordingBufferSlots, RecBufId);
generic_newtype_asref!(RecordingBufferSlots);
generic_newtype_asmut!(RecordingBufferSlots);
generic_newtype_deref!(RecordingBufferSlots, 8);
generic_newtype_deref_mut!(RecordingBufferSlots);
generic_newtype_index!(RecordingBufferSlots);
generic_newtype_index_mut!(RecordingBufferSlots);

impl<T: Defaults<[T; 8]> + Default> Default for RecordingBufferSlots<T> {
    fn default() -> Self {
        Self(T::defaults())
    }
}

impl<const N: usize, T: Default> Defaults<[Self; N]> for RecordingBufferSlots<T> {
    fn defaults() -> [Self; N]
    where
        Self: Default,
    {
        from_fn(|_| Self::default())
    }
}

impl<T> RecordingBufferSlots<T> {
    pub fn new(value: [T; 8]) -> Self {
        Self(value)
    }
}

impl<'de, T: Deserialize<'de>> Deserialize<'de> for RecordingBufferSlots<T> {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        Ok(Self(<[T; 8] as BigArray<T>>::deserialize(deserializer)?))
    }
}

impl<T: Serialize> Serialize for RecordingBufferSlots<T> {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        <[T; 8] as BigArray<T>>::serialize(&self.0, serializer)
    }
}

/// Generic collection for all slots data -- flex, static and recording buffers.
///
/// See the explanation in [`PlaybackSlots`] for why [`RecordingBufferSlots`] are handled
/// differently to [`PlaybackSlots`].
///
/// # [`Serialize`] / [`Deserialize`]
///
/// The `project.*` text file(s) are parsed differently to binary `markers.*` file(s).
/// As a result, this type does not have a generic [`Serialize`] / [`Deserialize`] implementations.
/// Rather, it has TODO
#[derive(Clone, Debug, Eq, PartialEq, Ord, PartialOrd, Hash)]
pub struct Slots<T> {
    // order is on purpose -- this is the order in the MarkersFile, which will be more authoritative
    // regarding slot data ordering than ProjectFile.
    pub flex_slots: PlaybackSlots<T>,
    pub recording_buffers: RecordingBufferSlots<T>,
    pub static_slots: PlaybackSlots<T>,
}

impl<T> Slots<T> {
    pub fn new(
        flex_slots: PlaybackSlots<T>,
        recording_buffers: RecordingBufferSlots<T>,
        static_slots: PlaybackSlots<T>,
    ) -> Self {
        Self {
            flex_slots,
            recording_buffers,
            static_slots,
        }
    }
}

/// Convenience type for combining [`SlotAttributes`] and [`SlotMarkers`],
/// or types which have the respective [`AsRef`] trait implemented.
/// This essentially gives you a type representative of the Octatrack's slot editing pages
/// -- all markers data and all attributes data.
#[derive(Default, Clone, Copy, PartialEq, Debug, Hash, PartialOrd, Ord, Eq)]
pub struct ActiveSlot<A, M>
where
    A: AsRef<SlotAttributes>,
    M: AsRef<SlotMarkers>,
{
    pub attrs: A,
    pub marks: M,
}

impl AsRef<ActiveSlot<SlotAttributes, SlotMarkers>> for ActiveSlot<SlotAttributes, SlotMarkers> {
    fn as_ref(&self) -> &ActiveSlot<SlotAttributes, SlotMarkers> {
        self
    }
}

impl<A, M> ActiveSlot<A, M>
where
    A: AsRef<SlotAttributes>,
    M: AsRef<SlotMarkers>,
{
    /// Creates a new [`ActiveSlot`] instance from the two component slots data types.
    ///
    /// # `AsRef`
    ///
    /// This method accepts any input type where, for each respective argument,
    /// `AsRef<SlotSlotAttributes>` or `AsRef<SlotSlotMarkers>` has been implemented appropriately.
    /// Therefore, any type that can be `AsRef`'d into one of these types is accepted as the
    /// relevant argument.
    ///
    /// # [`SlotAttributes`] example
    ///
    /// ```
    /// use ot_tools_io::types::ActiveSlot;
    /// use ot_tools_io::types::SlotAttributes;
    /// use ot_tools_io::types::SlotMarkers;
    /// # use ot_tools_io::types::SlotType;
    ///
    /// // example data
    /// let attrs = SlotAttributes {
    ///     slot_type: SlotType::Static,
    ///     slot_id: 1,
    ///     path: None,
    ///     timestrech_mode: Default::default(),
    ///     loop_mode: Default::default(),
    ///     trig_quantization_mode: Default::default(),
    ///     gain: 48,
    ///     bpm: 2880
    /// };
    ///
    /// pub struct AttrsNewType(SlotAttributes);
    ///
    /// impl AsRef<SlotAttributes> for AttrsNewType {
    ///     fn as_ref(&self) -> &SlotAttributes {
    ///         &self.0
    ///     }
    /// }
    ///
    /// ActiveSlot::new(AttrsNewType(attrs), SlotMarkers::default());
    /// ```
    ///
    /// # [`SlotMarkers`] example
    ///
    /// ```
    /// use ot_tools_io::types::SlotMarkers;
    /// use ot_tools_io::types::ActiveSlot;
    /// # use ot_tools_io::types::SlotType;
    /// # use ot_tools_io::types::SlotAttributes;
    /// #
    /// # let attrs = SlotAttributes {
    /// #     slot_type: SlotType::Static,
    /// #     slot_id: 1,
    /// #     path: None,
    /// #     timestrech_mode: Default::default(),
    /// #     loop_mode: Default::default(),
    /// #     trig_quantization_mode: Default::default(),
    /// #     gain: 48,
    /// #     bpm: 2880
    /// # };
    ///
    /// let marks = SlotMarkers::default();
    ///
    /// pub struct MarksNewType(SlotMarkers);
    ///
    /// impl AsRef<SlotMarkers> for MarksNewType {
    ///     fn as_ref(&self) -> &SlotMarkers {
    ///         &self.0
    ///     }
    /// }
    ///
    /// // can use the type as an input here
    /// ActiveSlot::new(attrs, MarksNewType(marks));
    /// ```
    pub fn new(attrs: A, marks: M) -> Self {
        Self { attrs, marks }
    }

    /// getter for attributes data
    pub fn attrs(self) -> A {
        self.attrs
    }

    pub fn attrs_ref(&self) -> &A {
        &self.attrs
    }

    /// reference getter for markers data
    pub fn marks(self) -> M {
        self.marks
    }

    /// reference getter for markers data
    pub fn marks_ref(&self) -> &M {
        &self.marks
    }
}

impl<A, M> ActiveSlot<A, M>
where
    A: AsRef<SlotAttributes> + AsMut<SlotAttributes>,
    M: AsRef<SlotMarkers> + AsMut<SlotMarkers>,
{
    /// mutable reference getter for attributes data
    pub fn attrs_mut(&mut self) -> &mut A {
        &mut self.attrs
    }

    /// mutable reference getter for markers data
    pub fn marks_mut(&mut self) -> &mut M {
        &mut self.marks
    }
}

// todo: ActiveSlot<A, M> -> ActiveSlot<Attrs, Marks>
//       ... apparently From<T> -> T exists in core
//       ... so how should this be called? do i even need to implement it?

impl<A, M> From<ActiveSlot<A, M>> for SampleSettingsFile
where
    A: AsRef<SlotAttributes>,
    M: AsRef<SlotMarkers>,
{
    fn from(value: ActiveSlot<A, M>) -> Self {
        SampleSettingsFile::from((value.attrs_ref(), value.marks_ref()))
    }
}

impl<A, M> TryFrom<Option<ActiveSlot<A, M>>> for SampleSettingsFile
where
    A: AsRef<SlotAttributes>,
    M: AsRef<SlotMarkers>,
{
    type Error = OtToolsIoError;
    fn try_from(value: Option<ActiveSlot<A, M>>) -> Result<Self, Self::Error> {
        // todo: error
        let value = value.ok_or(OtToolsIoError::InvalidIndex)?;
        Ok(SampleSettingsFile::from((
            value.attrs_ref(),
            value.marks_ref(),
        )))
    }
}