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
#![doc = include_str!("../README.md")]
#![deny(
    rustdoc::broken_intra_doc_links,
    rustdoc::private_intra_doc_links,
    rustdoc::missing_crate_level_docs,
    rustdoc::invalid_codeblock_attributes,
    rustdoc::invalid_rust_codeblocks,
    rustdoc::bare_urls,
    rustdoc::invalid_html_tags
)]
#![warn(
    trivial_casts,
    trivial_numeric_casts,
    unused_lifetimes,
    unused_import_braces,
    unreachable_pub,
    clippy::dbg_macro
)]
#![allow(clippy::type_complexity)]

use std::borrow::Cow;
use std::iter::FusedIterator;
use std::num::Wrapping;
use std::ops::Range;

use bevy_app::prelude::*;
use bevy_ecs::prelude::*;
use tracing::{debug, warn};
use valence_server::client::{Client, FlushPacketsSet, SpawnClientsSet};
use valence_server::event_loop::{EventLoopPreUpdate, PacketEvent};
pub use valence_server::protocol::packets::play::click_slot_c2s::{ClickMode, SlotChange};
use valence_server::protocol::packets::play::open_screen_s2c::WindowType;
pub use valence_server::protocol::packets::play::player_action_c2s::PlayerAction;
use valence_server::protocol::packets::play::{
    ClickSlotC2s, CloseHandledScreenC2s, CloseScreenS2c, CreativeInventoryActionC2s, InventoryS2c,
    OpenScreenS2c, PlayerActionC2s, ScreenHandlerSlotUpdateS2c, UpdateSelectedSlotC2s,
};
use valence_server::protocol::{VarInt, WritePacket};
use valence_server::text::IntoText;
use valence_server::{GameMode, ItemKind, ItemStack, Text};

mod validate;

pub struct InventoryPlugin;

impl Plugin for InventoryPlugin {
    fn build(&self, app: &mut bevy_app::App) {
        app.add_systems(
            PreUpdate,
            init_new_client_inventories.after(SpawnClientsSet),
        )
        .add_systems(
            PostUpdate,
            (
                update_client_on_close_inventory.before(update_open_inventories),
                update_open_inventories,
                update_player_inventories,
            )
                .before(FlushPacketsSet),
        )
        .add_systems(
            EventLoopPreUpdate,
            (
                handle_update_selected_slot,
                handle_click_slot,
                handle_creative_inventory_action,
                handle_close_handled_screen,
                handle_player_actions,
            ),
        )
        .init_resource::<InventorySettings>()
        .add_event::<ClickSlotEvent>()
        .add_event::<DropItemStackEvent>()
        .add_event::<CreativeInventoryActionEvent>()
        .add_event::<UpdateSelectedSlotEvent>();
    }
}

/// The number of slots in the "main" part of the player inventory. 3 rows of 9,
/// plus the hotbar.
pub const PLAYER_INVENTORY_MAIN_SLOTS_COUNT: u16 = 36;

#[derive(Debug, Clone, Component)]
pub struct Inventory {
    title: Text,
    kind: InventoryKind,
    slots: Box<[Option<ItemStack>]>,
    /// Contains a set bit for each modified slot in `slots`.
    #[doc(hidden)]
    pub changed: u64,
}

impl Inventory {
    pub fn new(kind: InventoryKind) -> Self {
        // TODO: default title to the correct translation key instead
        Self::with_title(kind, "Inventory")
    }

    pub fn with_title<'a>(kind: InventoryKind, title: impl IntoText<'a>) -> Self {
        Inventory {
            title: title.into_cow_text().into_owned(),
            kind,
            slots: vec![None; kind.slot_count()].into(),
            changed: 0,
        }
    }

    #[track_caller]
    pub fn slot(&self, idx: u16) -> Option<&ItemStack> {
        self.slots
            .get(idx as usize)
            .expect("slot index out of range")
            .as_ref()
    }

    /// Sets the slot at the given index to the given item stack.
    ///
    /// See also [`Inventory::replace_slot`].
    ///
    /// ```
    /// # use valence_inventory::*;
    /// # use valence_server::item::{ItemStack, ItemKind};
    /// let mut inv = Inventory::new(InventoryKind::Generic9x1);
    /// inv.set_slot(0, ItemStack::new(ItemKind::Diamond, 1, None));
    /// assert_eq!(inv.slot(0).unwrap().item, ItemKind::Diamond);
    /// ```
    #[track_caller]
    #[inline]
    pub fn set_slot(&mut self, idx: u16, item: impl Into<Option<ItemStack>>) {
        let _ = self.replace_slot(idx, item);
    }

    /// Replaces the slot at the given index with the given item stack, and
    /// returns the old stack in that slot.
    ///
    /// See also [`Inventory::set_slot`].
    ///
    /// ```
    /// # use valence_inventory::*;
    /// # use valence_server::item::{ItemStack, ItemKind};
    /// let mut inv = Inventory::new(InventoryKind::Generic9x1);
    /// inv.set_slot(0, ItemStack::new(ItemKind::Diamond, 1, None));
    /// let old = inv.replace_slot(0, ItemStack::new(ItemKind::IronIngot, 1, None));
    /// assert_eq!(old.unwrap().item, ItemKind::Diamond);
    /// ```
    #[track_caller]
    #[must_use]
    pub fn replace_slot(
        &mut self,
        idx: u16,
        item: impl Into<Option<ItemStack>>,
    ) -> Option<ItemStack> {
        assert!(idx < self.slot_count(), "slot index of {idx} out of bounds");

        let new = item.into();
        let old = &mut self.slots[idx as usize];

        if new != *old {
            self.changed |= 1 << idx;
        }

        std::mem::replace(old, new)
    }

    /// Swap the contents of two slots. If the slots are the same, nothing
    /// happens.
    ///
    /// ```
    /// # use valence_inventory::*;
    /// # use valence_server::item::{ItemStack, ItemKind};
    /// let mut inv = Inventory::new(InventoryKind::Generic9x1);
    /// inv.set_slot(0, ItemStack::new(ItemKind::Diamond, 1, None));
    /// assert_eq!(inv.slot(1), None);
    /// inv.swap_slot(0, 1);
    /// assert_eq!(inv.slot(1).unwrap().item, ItemKind::Diamond);
    /// ```
    #[track_caller]
    pub fn swap_slot(&mut self, idx_a: u16, idx_b: u16) {
        assert!(
            idx_a < self.slot_count(),
            "slot index of {idx_a} out of bounds"
        );
        assert!(
            idx_b < self.slot_count(),
            "slot index of {idx_b} out of bounds"
        );

        if idx_a == idx_b || self.slots[idx_a as usize] == self.slots[idx_b as usize] {
            // Nothing to do here, ignore.
            return;
        }

        self.changed |= 1 << idx_a;
        self.changed |= 1 << idx_b;

        self.slots.swap(idx_a as usize, idx_b as usize);
    }

    /// Set the amount of items in the given slot without replacing the slot
    /// entirely. Valid values are 1-127, inclusive, and `amount` will be
    /// clamped to this range. If the slot is empty, nothing happens.
    ///
    /// ```
    /// # use valence_inventory::*;
    /// # use valence_server::item::{ItemStack, ItemKind};
    /// let mut inv = Inventory::new(InventoryKind::Generic9x1);
    /// inv.set_slot(0, ItemStack::new(ItemKind::Diamond, 1, None));
    /// inv.set_slot_amount(0, 64);
    /// assert_eq!(inv.slot(0).unwrap().count(), 64);
    /// ```
    #[track_caller]
    pub fn set_slot_amount(&mut self, idx: u16, amount: u8) {
        assert!(idx < self.slot_count(), "slot index out of range");

        if let Some(item) = self.slots[idx as usize].as_mut() {
            if item.count() == amount {
                return;
            }
            item.set_count(amount);
            self.changed |= 1 << idx;
        }
    }

    pub fn slot_count(&self) -> u16 {
        self.slots.len() as u16
    }

    pub fn slots(
        &self,
    ) -> impl ExactSizeIterator<Item = Option<&ItemStack>>
           + DoubleEndedIterator
           + FusedIterator
           + Clone
           + '_ {
        self.slots.iter().map(|item| item.as_ref())
    }

    pub fn kind(&self) -> InventoryKind {
        self.kind
    }

    /// The text displayed on the inventory's title bar.
    ///
    /// ```
    /// # use valence_inventory::*;
    /// # use valence_server::item::{ItemStack, ItemKind};
    /// # use valence_server::text::Text;
    /// let inv = Inventory::with_title(InventoryKind::Generic9x3, "Box of Holding");
    /// assert_eq!(inv.title(), &Text::from("Box of Holding"));
    /// ```
    pub fn title(&self) -> &Text {
        &self.title
    }

    /// Set the text displayed on the inventory's title bar.
    ///
    /// To get the old title, use [`Inventory::replace_title`].
    ///
    /// ```
    /// # use valence_inventory::*;
    /// let mut inv = Inventory::new(InventoryKind::Generic9x3);
    /// inv.set_title("Box of Holding");
    /// ```
    #[inline]
    pub fn set_title<'a>(&mut self, title: impl IntoText<'a>) {
        let _ = self.replace_title(title);
    }

    /// Replace the text displayed on the inventory's title bar, and returns the
    /// old text.
    #[must_use]
    pub fn replace_title<'a>(&mut self, title: impl IntoText<'a>) -> Text {
        // TODO: set title modified flag
        std::mem::replace(&mut self.title, title.into_cow_text().into_owned())
    }

    pub(crate) fn slot_slice(&self) -> &[Option<ItemStack>] {
        self.slots.as_ref()
    }

    /// Returns the first empty slot in the given range, or `None` if there are
    /// no empty slots in the range.
    ///
    /// ```
    /// # use valence_inventory::*;
    /// # use valence_server::item::*;
    /// let mut inv = Inventory::new(InventoryKind::Generic9x1);
    /// inv.set_slot(0, ItemStack::new(ItemKind::Diamond, 1, None));
    /// inv.set_slot(2, ItemStack::new(ItemKind::GoldIngot, 1, None));
    /// inv.set_slot(3, ItemStack::new(ItemKind::IronIngot, 1, None));
    /// assert_eq!(inv.first_empty_slot_in(0..6), Some(1));
    /// assert_eq!(inv.first_empty_slot_in(2..6), Some(4));
    /// ```
    #[track_caller]
    #[must_use]
    pub fn first_empty_slot_in(&self, mut range: Range<u16>) -> Option<u16> {
        assert!(
            (0..=self.slot_count()).contains(&range.start)
                && (0..=self.slot_count()).contains(&range.end),
            "slot range out of range"
        );

        range.find(|&idx| self.slots[idx as usize].is_none())
    }

    /// Returns the first empty slot in the inventory, or `None` if there are no
    /// empty slots.
    /// ```
    /// # use valence_inventory::*;
    /// # use valence_server::item::*;
    /// let mut inv = Inventory::new(InventoryKind::Generic9x1);
    /// inv.set_slot(0, ItemStack::new(ItemKind::Diamond, 1, None));
    /// inv.set_slot(2, ItemStack::new(ItemKind::GoldIngot, 1, None));
    /// inv.set_slot(3, ItemStack::new(ItemKind::IronIngot, 1, None));
    /// assert_eq!(inv.first_empty_slot(), Some(1));
    /// ```
    #[inline]
    pub fn first_empty_slot(&self) -> Option<u16> {
        self.first_empty_slot_in(0..self.slot_count())
    }

    /// Returns the first slot with the given [`ItemKind`] in the inventory
    /// where `count() < stack_max`, or `None` if there are no empty slots.
    /// ```
    /// # use valence_inventory::*;
    /// # use valence_server::item::*;
    /// let mut inv = Inventory::new(InventoryKind::Generic9x1);
    /// inv.set_slot(0, ItemStack::new(ItemKind::Diamond, 1, None));
    /// inv.set_slot(2, ItemStack::new(ItemKind::GoldIngot, 64, None));
    /// inv.set_slot(3, ItemStack::new(ItemKind::IronIngot, 1, None));
    /// inv.set_slot(4, ItemStack::new(ItemKind::GoldIngot, 1, None));
    /// assert_eq!(
    ///     inv.first_slot_with_item_in(ItemKind::GoldIngot, 64, 0..5),
    ///     Some(4)
    /// );
    /// ```
    pub fn first_slot_with_item_in(
        &self,
        item: ItemKind,
        stack_max: u8,
        mut range: Range<u16>,
    ) -> Option<u16> {
        assert!(
            (0..=self.slot_count()).contains(&range.start)
                && (0..=self.slot_count()).contains(&range.end),
            "slot range out of range"
        );
        assert!(stack_max > 0, "stack_max must be greater than 0");

        range.find(|&idx| {
            self.slots[idx as usize]
                .as_ref()
                .map(|stack| stack.item == item && stack.count() < stack_max)
                .unwrap_or(false)
        })
    }

    /// Returns the first slot with the given [`ItemKind`] in the inventory
    /// where `count() < stack_max`, or `None` if there are no empty slots.
    /// ```
    /// # use valence_inventory::*;
    /// # use valence_server::item::*;
    /// let mut inv = Inventory::new(InventoryKind::Generic9x1);
    /// inv.set_slot(0, ItemStack::new(ItemKind::Diamond, 1, None));
    /// inv.set_slot(2, ItemStack::new(ItemKind::GoldIngot, 64, None));
    /// inv.set_slot(3, ItemStack::new(ItemKind::IronIngot, 1, None));
    /// inv.set_slot(4, ItemStack::new(ItemKind::GoldIngot, 1, None));
    /// assert_eq!(inv.first_slot_with_item(ItemKind::GoldIngot, 64), Some(4));
    /// ```
    #[inline]
    pub fn first_slot_with_item(&self, item: ItemKind, stack_max: u8) -> Option<u16> {
        self.first_slot_with_item_in(item, stack_max, 0..self.slot_count())
    }
}

/// Miscellaneous inventory data.
#[derive(Component, Debug)]
pub struct ClientInventoryState {
    /// The current window ID. Incremented when inventories are opened.
    window_id: u8,
    state_id: Wrapping<i32>,
    /// Tracks what slots have been changed by this client in this tick, so we
    /// don't need to send updates for them.
    slots_changed: u64,
    /// Whether the client has updated the cursor item in this tick. This is not
    /// on the `CursorItem` component to make maintaining accurate change
    /// detection for end users easier.
    client_updated_cursor_item: bool,
}

impl ClientInventoryState {
    #[doc(hidden)]
    pub fn window_id(&self) -> u8 {
        self.window_id
    }

    #[doc(hidden)]
    pub fn state_id(&self) -> Wrapping<i32> {
        self.state_id
    }
}

/// Indicates which hotbar slot the player is currently holding.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Component)]
pub struct HeldItem {
    held_item_slot: u16,
}

impl HeldItem {
    /// The slot ID of the currently held item, in the range 36-44 inclusive.
    /// This value is safe to use on the player's inventory directly.
    pub fn slot(&self) -> u16 {
        self.held_item_slot
    }
}

/// The item stack that the client thinks it's holding under the mouse
/// cursor.
#[derive(Component, Clone, PartialEq, Default, Debug)]
pub struct CursorItem(pub Option<ItemStack>);

/// Used to indicate that the client with this component is currently viewing
/// an inventory.
#[derive(Component, Clone, Debug)]
pub struct OpenInventory {
    /// The entity with the `Inventory` component that the client is currently
    /// viewing.
    pub entity: Entity,
    client_changed: u64,
}

impl OpenInventory {
    pub fn new(entity: Entity) -> Self {
        OpenInventory {
            entity,
            client_changed: 0,
        }
    }
}

/// A helper to represent the inventory window that the player is currently
/// viewing. Handles dispatching reads to the correct inventory.
///
/// This is a read-only version of [`InventoryWindowMut`].
///
/// ```
/// # use valence_inventory::*;
/// # use valence_server::item::*;
/// let mut player_inventory = Inventory::new(InventoryKind::Player);
/// player_inventory.set_slot(36, ItemStack::new(ItemKind::Diamond, 1, None));
///
/// let target_inventory = Inventory::new(InventoryKind::Generic9x3);
/// let window = InventoryWindow::new(&player_inventory, Some(&target_inventory));
///
/// assert_eq!(
///     window.slot(54),
///     Some(&ItemStack::new(ItemKind::Diamond, 1, None))
/// );
/// ```
pub struct InventoryWindow<'a> {
    player_inventory: &'a Inventory,
    open_inventory: Option<&'a Inventory>,
}

impl<'a> InventoryWindow<'a> {
    pub fn new(player_inventory: &'a Inventory, open_inventory: Option<&'a Inventory>) -> Self {
        Self {
            player_inventory,
            open_inventory,
        }
    }

    #[track_caller]
    pub fn slot(&self, idx: u16) -> Option<&ItemStack> {
        if let Some(open_inv) = self.open_inventory.as_ref() {
            if idx < open_inv.slot_count() {
                return open_inv.slot(idx);
            } else {
                return self
                    .player_inventory
                    .slot(convert_to_player_slot_id(open_inv.kind(), idx));
            }
        } else {
            return self.player_inventory.slot(idx);
        }
    }

    #[track_caller]
    pub fn slot_count(&self) -> u16 {
        match self.open_inventory.as_ref() {
            Some(inv) => inv.slot_count() + PLAYER_INVENTORY_MAIN_SLOTS_COUNT,
            None => self.player_inventory.slot_count(),
        }
    }
}

/// A helper to represent the inventory window that the player is currently
/// viewing. Handles dispatching reads/writes to the correct inventory.
///
/// This is a writable version of [`InventoryWindow`].
///
/// ```
/// # use valence_inventory::*;
/// # use valence_server::item::*;
/// let mut player_inventory = Inventory::new(InventoryKind::Player);
/// let mut target_inventory = Inventory::new(InventoryKind::Generic9x3);
/// let mut window = InventoryWindowMut::new(&mut player_inventory, Some(&mut target_inventory));
///
/// window.set_slot(54, ItemStack::new(ItemKind::Diamond, 1, None));
///
/// assert_eq!(
///     player_inventory.slot(36),
///     Some(&ItemStack::new(ItemKind::Diamond, 1, None))
/// );
/// ```
pub struct InventoryWindowMut<'a> {
    player_inventory: &'a mut Inventory,
    open_inventory: Option<&'a mut Inventory>,
}

impl<'a> InventoryWindowMut<'a> {
    pub fn new(
        player_inventory: &'a mut Inventory,
        open_inventory: Option<&'a mut Inventory>,
    ) -> Self {
        Self {
            player_inventory,
            open_inventory,
        }
    }

    #[track_caller]
    pub fn slot(&self, idx: u16) -> Option<&ItemStack> {
        if let Some(open_inv) = self.open_inventory.as_ref() {
            if idx < open_inv.slot_count() {
                return open_inv.slot(idx);
            } else {
                return self
                    .player_inventory
                    .slot(convert_to_player_slot_id(open_inv.kind(), idx));
            }
        } else {
            return self.player_inventory.slot(idx);
        }
    }

    #[track_caller]
    #[must_use]
    pub fn replace_slot(
        &mut self,
        idx: u16,
        item: impl Into<Option<ItemStack>>,
    ) -> Option<ItemStack> {
        assert!(idx < self.slot_count(), "slot index of {idx} out of bounds");

        if let Some(open_inv) = self.open_inventory.as_mut() {
            if idx < open_inv.slot_count() {
                open_inv.replace_slot(idx, item)
            } else {
                self.player_inventory
                    .replace_slot(convert_to_player_slot_id(open_inv.kind(), idx), item)
            }
        } else {
            self.player_inventory.replace_slot(idx, item)
        }
    }

    #[track_caller]
    #[inline]
    pub fn set_slot(&mut self, idx: u16, item: impl Into<Option<ItemStack>>) {
        let _ = self.replace_slot(idx, item);
    }

    pub fn slot_count(&self) -> u16 {
        match self.open_inventory.as_ref() {
            Some(inv) => inv.slot_count() + PLAYER_INVENTORY_MAIN_SLOTS_COUNT,
            None => self.player_inventory.slot_count(),
        }
    }
}

/// Attach the necessary inventory components to new clients.
fn init_new_client_inventories(clients: Query<Entity, Added<Client>>, mut commands: Commands) {
    for entity in &clients {
        commands.entity(entity).insert((
            Inventory::new(InventoryKind::Player),
            CursorItem(None),
            ClientInventoryState {
                window_id: 0,
                state_id: Wrapping(0),
                slots_changed: 0,
                client_updated_cursor_item: false,
            },
            HeldItem {
                // First slot of the hotbar.
                held_item_slot: 36,
            },
        ));
    }
}

/// Send updates for each client's player inventory.
fn update_player_inventories(
    mut query: Query<
        (
            &mut Inventory,
            &mut Client,
            &mut ClientInventoryState,
            Ref<CursorItem>,
        ),
        Without<OpenInventory>,
    >,
) {
    for (mut inventory, mut client, mut inv_state, cursor_item) in &mut query {
        if inventory.kind != InventoryKind::Player {
            warn!("Inventory on client entity is not a player inventory");
        }

        if inventory.changed == u64::MAX {
            // Update the whole inventory.

            inv_state.state_id += 1;

            client.write_packet(&InventoryS2c {
                window_id: 0,
                state_id: VarInt(inv_state.state_id.0),
                slots: Cow::Borrowed(inventory.slot_slice()),
                carried_item: Cow::Borrowed(&cursor_item.0),
            });

            inventory.changed = 0;
            inv_state.slots_changed = 0;

            // Skip updating the cursor item because we just updated the whole inventory.
            continue;
        } else if inventory.changed != 0 {
            // Send the modified slots.

            // The slots that were NOT modified by this client, and they need to be sent
            let changed_filtered = inventory.changed & !inv_state.slots_changed;

            if changed_filtered != 0 {
                inv_state.state_id += 1;

                for (i, slot) in inventory.slots.iter().enumerate() {
                    if ((changed_filtered >> i) & 1) == 1 {
                        client.write_packet(&ScreenHandlerSlotUpdateS2c {
                            window_id: 0,
                            state_id: VarInt(inv_state.state_id.0),
                            slot_idx: i as i16,
                            slot_data: Cow::Borrowed(slot),
                        });
                    }
                }
            }

            inventory.changed = 0;
            inv_state.slots_changed = 0;
        }

        if cursor_item.is_changed() && !inv_state.client_updated_cursor_item {
            // Contrary to what you might think, we actually don't want to increment the
            // state ID here because the client doesn't actually acknowledge the
            // state_id change for this packet specifically. See #304.

            client.write_packet(&ScreenHandlerSlotUpdateS2c {
                window_id: -1,
                state_id: VarInt(inv_state.state_id.0),
                slot_idx: -1,
                slot_data: Cow::Borrowed(&cursor_item.0),
            });
        }

        inv_state.client_updated_cursor_item = false;
    }
}

/// Handles the `OpenInventory` component being added to a client, which
/// indicates that the client is now viewing an inventory, and sends inventory
/// updates to the client when the inventory is modified.
fn update_open_inventories(
    mut clients: Query<(
        Entity,
        &mut Client,
        &mut ClientInventoryState,
        &CursorItem,
        &mut OpenInventory,
    )>,
    mut inventories: Query<&mut Inventory>,
    mut commands: Commands,
) {
    // These operations need to happen in this order.

    // Send the inventory contents to all clients that are viewing an inventory.
    for (client_entity, mut client, mut inv_state, cursor_item, mut open_inventory) in &mut clients
    {
        // Validate that the inventory exists.
        let Ok(mut inventory) = inventories.get_mut(open_inventory.entity) else {
            // The inventory no longer exists, so close the inventory.
            commands.entity(client_entity).remove::<OpenInventory>();

            client.write_packet(&CloseScreenS2c {
                window_id: inv_state.window_id,
            });

            continue;
        };

        if open_inventory.is_added() {
            // Send the inventory to the client if the client just opened the inventory.
            inv_state.window_id = inv_state.window_id % 100 + 1;
            open_inventory.client_changed = 0;

            client.write_packet(&OpenScreenS2c {
                window_id: VarInt(inv_state.window_id.into()),
                window_type: WindowType::from(inventory.kind),
                window_title: Cow::Borrowed(&inventory.title),
            });

            client.write_packet(&InventoryS2c {
                window_id: inv_state.window_id,
                state_id: VarInt(inv_state.state_id.0),
                slots: Cow::Borrowed(inventory.slot_slice()),
                carried_item: Cow::Borrowed(&cursor_item.0),
            });
        } else {
            // The client is already viewing the inventory.

            if inventory.changed == u64::MAX {
                // Send the entire inventory.

                inv_state.state_id += 1;

                client.write_packet(&InventoryS2c {
                    window_id: inv_state.window_id,
                    state_id: VarInt(inv_state.state_id.0),
                    slots: Cow::Borrowed(inventory.slot_slice()),
                    carried_item: Cow::Borrowed(&cursor_item.0),
                })
            } else {
                // Send the changed slots.

                // The slots that were NOT changed by this client, and they need to be sent.
                let changed_filtered = inventory.changed & !open_inventory.client_changed;

                if changed_filtered != 0 {
                    inv_state.state_id += 1;

                    for (i, slot) in inventory.slots.iter().enumerate() {
                        if (changed_filtered >> i) & 1 == 1 {
                            client.write_packet(&ScreenHandlerSlotUpdateS2c {
                                window_id: inv_state.window_id as i8,
                                state_id: VarInt(inv_state.state_id.0),
                                slot_idx: i as i16,
                                slot_data: Cow::Borrowed(slot),
                            });
                        }
                    }
                }
            }
        }

        open_inventory.client_changed = 0;
        inv_state.slots_changed = 0;
        inv_state.client_updated_cursor_item = false;
        inventory.changed = 0;
    }
}

/// Handles clients telling the server that they are closing an inventory.
fn handle_close_handled_screen(mut packets: EventReader<PacketEvent>, mut commands: Commands) {
    for packet in packets.iter() {
        if packet.decode::<CloseHandledScreenC2s>().is_some() {
            if let Some(mut entity) = commands.get_entity(packet.client) {
                entity.remove::<OpenInventory>();
            }
        }
    }
}

/// Detects when a client's `OpenInventory` component is removed, which
/// indicates that the client is no longer viewing an inventory.
fn update_client_on_close_inventory(
    mut removals: RemovedComponents<OpenInventory>,
    mut clients: Query<(&mut Client, &ClientInventoryState)>,
) {
    for entity in &mut removals {
        if let Ok((mut client, inv_state)) = clients.get_mut(entity) {
            client.write_packet(&CloseScreenS2c {
                window_id: inv_state.window_id,
            })
        }
    }
}

// TODO: make this event user friendly.
#[derive(Event, Clone, Debug)]
pub struct ClickSlotEvent {
    pub client: Entity,
    pub window_id: u8,
    pub state_id: i32,
    pub slot_id: i16,
    pub button: i8,
    pub mode: ClickMode,
    pub slot_changes: Vec<SlotChange>,
    pub carried_item: Option<ItemStack>,
}

#[derive(Event, Clone, Debug)]
pub struct DropItemStackEvent {
    pub client: Entity,
    pub from_slot: Option<u16>,
    pub stack: ItemStack,
}

fn handle_click_slot(
    mut packets: EventReader<PacketEvent>,
    mut clients: Query<(
        &mut Client,
        &mut Inventory,
        &mut ClientInventoryState,
        Option<&mut OpenInventory>,
        &mut CursorItem,
    )>,
    mut inventories: Query<&mut Inventory, Without<Client>>,
    mut drop_item_stack_events: EventWriter<DropItemStackEvent>,
    mut click_slot_events: EventWriter<ClickSlotEvent>,
) {
    for packet in packets.iter() {
        let Some(pkt) = packet.decode::<ClickSlotC2s>() else {
            // Not the packet we're looking for.
            continue;
        };

        let Ok((mut client, mut client_inv, mut inv_state, open_inventory, mut cursor_item)) =
            clients.get_mut(packet.client)
        else {
            // The client does not exist, ignore.
            continue;
        };

        let open_inv = open_inventory
            .as_ref()
            .and_then(|open| inventories.get_mut(open.entity).ok());

        if let Err(e) = validate::validate_click_slot_packet(
            &pkt,
            &client_inv,
            open_inv.as_deref(),
            &cursor_item,
        ) {
            debug!(
                "failed to validate click slot packet for client {:#?}: \"{e:#}\" {pkt:#?}",
                packet.client
            );

            // Resync the inventory.

            client.write_packet(&InventoryS2c {
                window_id: if open_inv.is_some() {
                    inv_state.window_id
                } else {
                    0
                },
                state_id: VarInt(inv_state.state_id.0),
                slots: Cow::Borrowed(open_inv.unwrap_or(client_inv).slot_slice()),
                carried_item: Cow::Borrowed(&cursor_item.0),
            });

            continue;
        }

        if pkt.slot_idx < 0 && pkt.mode == ClickMode::Click {
            // The client is dropping the cursor item by clicking outside the window.

            if let Some(stack) = cursor_item.0.take() {
                drop_item_stack_events.send(DropItemStackEvent {
                    client: packet.client,
                    from_slot: None,
                    stack,
                });
            }
        } else if pkt.mode == ClickMode::DropKey {
            // The client is dropping an item by pressing the drop key.

            let entire_stack = pkt.button == 1;

            // Needs to open the inventory for if the player is dropping an item while
            // having an inventory open.
            if let Some(open_inventory) = open_inventory {
                // The player is interacting with an inventory that is open.

                let Ok(mut target_inventory) = inventories.get_mut(open_inventory.entity) else {
                    // The inventory does not exist, ignore.
                    continue;
                };

                if inv_state.state_id.0 != pkt.state_id.0 {
                    // Client is out of sync. Resync and ignore click.

                    debug!("Client state id mismatch, resyncing");

                    inv_state.state_id += 1;

                    client.write_packet(&InventoryS2c {
                        window_id: inv_state.window_id,
                        state_id: VarInt(inv_state.state_id.0),
                        slots: Cow::Borrowed(target_inventory.slot_slice()),
                        carried_item: Cow::Borrowed(&cursor_item.0),
                    });

                    continue;
                }

                if (0i16..target_inventory.slot_count() as i16).contains(&pkt.slot_idx) {
                    // The player is dropping an item from another inventory.

                    if let Some(stack) = target_inventory.slot(pkt.slot_idx as u16) {
                        let dropped = if entire_stack || stack.count() == 1 {
                            target_inventory.replace_slot(pkt.slot_idx as u16, None)
                        } else {
                            let mut stack = stack.clone();
                            stack.set_count(stack.count() - 1);
                            let mut old_slot =
                                target_inventory.replace_slot(pkt.slot_idx as u16, Some(stack));
                            // we already checked that the slot was not empty and that the
                            // stack count is > 1
                            old_slot.as_mut().unwrap().set_count(1);
                            old_slot
                        }
                        .expect("dropped item should exist"); // we already checked that the slot was not empty

                        drop_item_stack_events.send(DropItemStackEvent {
                            client: packet.client,
                            from_slot: Some(pkt.slot_idx as u16),
                            stack: dropped,
                        });
                    }
                } else {
                    // The player is dropping an item from their inventory.
                    let slot_id =
                        convert_to_player_slot_id(target_inventory.kind, pkt.slot_idx as u16);
                    if let Some(stack) = client_inv.slot(slot_id) {
                        let dropped = if entire_stack || stack.count() == 1 {
                            client_inv.replace_slot(slot_id, None)
                        } else {
                            let mut stack = stack.clone();
                            stack.set_count(stack.count() - 1);
                            let mut old_slot = client_inv.replace_slot(slot_id, Some(stack));
                            // we already checked that the slot was not empty and that the
                            // stack count is > 1
                            old_slot.as_mut().unwrap().set_count(1);
                            old_slot
                        }
                        .expect("dropped item should exist"); // we already checked that the slot was not empty

                        drop_item_stack_events.send(DropItemStackEvent {
                            client: packet.client,
                            from_slot: Some(slot_id),
                            stack: dropped,
                        });
                    }
                }
            } else {
                // The player has no inventory open and is dropping an item from their
                // inventory.
                if let Some(stack) = client_inv.slot(pkt.slot_idx as u16) {
                    let dropped = if entire_stack || stack.count() == 1 {
                        client_inv.replace_slot(pkt.slot_idx as u16, None)
                    } else {
                        let mut stack = stack.clone();
                        stack.set_count(stack.count() - 1);
                        let mut old_slot =
                            client_inv.replace_slot(pkt.slot_idx as u16, Some(stack));
                        // we already checked that the slot was not empty and that the
                        // stack count is > 1
                        old_slot.as_mut().unwrap().set_count(1);
                        old_slot
                    }
                    .expect("dropped item should exist"); // we already checked that the slot was not empty

                    drop_item_stack_events.send(DropItemStackEvent {
                        client: packet.client,
                        from_slot: Some(pkt.slot_idx as u16),
                        stack: dropped,
                    });
                }
            }
        } else {
            // The player is clicking a slot in an inventory.

            // Validate the window id.
            if (pkt.window_id == 0) != open_inventory.is_none() {
                warn!(
                    "Client sent a click with an invalid window id for current state: window_id = \
                     {}, open_inventory present = {}",
                    pkt.window_id,
                    open_inventory.is_some()
                );
                continue;
            }

            if let Some(mut open_inventory) = open_inventory {
                // The player is interacting with an inventory that is open.

                let Ok(mut target_inventory) = inventories.get_mut(open_inventory.entity) else {
                    // The inventory does not exist, ignore.
                    continue;
                };

                if inv_state.state_id.0 != pkt.state_id.0 {
                    // Client is out of sync. Resync and ignore click.

                    debug!("Client state id mismatch, resyncing");

                    inv_state.state_id += 1;

                    client.write_packet(&InventoryS2c {
                        window_id: inv_state.window_id,
                        state_id: VarInt(inv_state.state_id.0),
                        slots: Cow::Borrowed(target_inventory.slot_slice()),
                        carried_item: Cow::Borrowed(&cursor_item.0),
                    });

                    continue;
                }

                cursor_item.set_if_neq(CursorItem(pkt.carried_item.clone()));

                for slot in pkt.slot_changes.clone() {
                    if (0i16..target_inventory.slot_count() as i16).contains(&slot.idx) {
                        // The client is interacting with a slot in the target inventory.
                        target_inventory.set_slot(slot.idx as u16, slot.item);
                        open_inventory.client_changed |= 1 << slot.idx;
                    } else {
                        // The client is interacting with a slot in their own inventory.
                        let slot_id =
                            convert_to_player_slot_id(target_inventory.kind, slot.idx as u16);
                        client_inv.set_slot(slot_id, slot.item);
                        inv_state.slots_changed |= 1 << slot_id;
                    }
                }
            } else {
                // The client is interacting with their own inventory.

                if inv_state.state_id.0 != pkt.state_id.0 {
                    // Client is out of sync. Resync and ignore the click.

                    debug!("Client state id mismatch, resyncing");

                    inv_state.state_id += 1;

                    client.write_packet(&InventoryS2c {
                        window_id: inv_state.window_id,
                        state_id: VarInt(inv_state.state_id.0),
                        slots: Cow::Borrowed(client_inv.slot_slice()),
                        carried_item: Cow::Borrowed(&cursor_item.0),
                    });

                    continue;
                }

                cursor_item.set_if_neq(CursorItem(pkt.carried_item.clone()));
                inv_state.client_updated_cursor_item = true;

                for slot in pkt.slot_changes.clone() {
                    if (0i16..client_inv.slot_count() as i16).contains(&slot.idx) {
                        client_inv.set_slot(slot.idx as u16, slot.item);
                        inv_state.slots_changed |= 1 << slot.idx;
                    } else {
                        // The client is trying to interact with a slot that does not exist,
                        // ignore.
                        warn!(
                            "Client attempted to interact with slot {} which does not exist",
                            slot.idx
                        );
                    }
                }
            }

            click_slot_events.send(ClickSlotEvent {
                client: packet.client,
                window_id: pkt.window_id,
                state_id: pkt.state_id.0,
                slot_id: pkt.slot_idx,
                button: pkt.button,
                mode: pkt.mode,
                slot_changes: pkt.slot_changes,
                carried_item: pkt.carried_item,
            });
        }
    }
}

fn handle_player_actions(
    mut packets: EventReader<PacketEvent>,
    mut clients: Query<(&mut Inventory, &mut ClientInventoryState, &HeldItem)>,
    mut drop_item_stack_events: EventWriter<DropItemStackEvent>,
) {
    for packet in packets.iter() {
        if let Some(pkt) = packet.decode::<PlayerActionC2s>() {
            match pkt.action {
                PlayerAction::DropAllItems => {
                    if let Ok((mut inv, mut inv_state, &held)) = clients.get_mut(packet.client) {
                        if let Some(stack) = inv.replace_slot(held.slot(), None) {
                            inv_state.slots_changed |= 1 << held.slot();

                            drop_item_stack_events.send(DropItemStackEvent {
                                client: packet.client,
                                from_slot: Some(held.slot()),
                                stack,
                            });
                        }
                    }
                }
                PlayerAction::DropItem => {
                    if let Ok((mut inv, mut inv_state, held)) = clients.get_mut(packet.client) {
                        if let Some(mut stack) = inv.replace_slot(held.slot(), None) {
                            if stack.count() > 1 {
                                inv.set_slot(
                                    held.slot(),
                                    stack.clone().with_count(stack.count() - 1),
                                );

                                stack.set_count(1);
                            }

                            inv_state.slots_changed |= 1 << held.slot();

                            drop_item_stack_events.send(DropItemStackEvent {
                                client: packet.client,
                                from_slot: Some(held.slot()),
                                stack,
                            })
                        }
                    }
                }
                PlayerAction::SwapItemWithOffhand => {
                    // TODO
                }
                _ => {}
            }
        }
    }
}

// TODO: make this event user friendly.
#[derive(Event, Clone, Debug)]
pub struct CreativeInventoryActionEvent {
    pub client: Entity,
    pub slot: i16,
    pub clicked_item: Option<ItemStack>,
}

fn handle_creative_inventory_action(
    mut packets: EventReader<PacketEvent>,
    mut clients: Query<(
        &mut Client,
        &mut Inventory,
        &mut ClientInventoryState,
        &GameMode,
    )>,
    mut inv_action_events: EventWriter<CreativeInventoryActionEvent>,
    mut drop_item_stack_events: EventWriter<DropItemStackEvent>,
) {
    for packet in packets.iter() {
        if let Some(pkt) = packet.decode::<CreativeInventoryActionC2s>() {
            let Ok((mut client, mut inventory, mut inv_state, game_mode)) =
                clients.get_mut(packet.client)
            else {
                continue;
            };

            if *game_mode != GameMode::Creative {
                // The client is not in creative mode, ignore.
                continue;
            }

            if pkt.slot == -1 {
                if let Some(stack) = pkt.clicked_item.clone() {
                    drop_item_stack_events.send(DropItemStackEvent {
                        client: packet.client,
                        from_slot: None,
                        stack,
                    });
                }
                continue;
            }

            if pkt.slot < 0 || pkt.slot >= inventory.slot_count() as i16 {
                // The client is trying to interact with a slot that does not exist, ignore.
                continue;
            }

            // Set the slot without marking it as changed.
            inventory.slots[pkt.slot as usize] = pkt.clicked_item.clone();

            inv_state.state_id += 1;

            // HACK: notchian clients rely on the server to send the slot update when in
            // creative mode. Simply marking the slot as changed is not enough. This was
            // discovered because shift-clicking the destroy item slot in creative mode does
            // not work without this hack.
            client.write_packet(&ScreenHandlerSlotUpdateS2c {
                window_id: 0,
                state_id: VarInt(inv_state.state_id.0),
                slot_idx: pkt.slot,
                slot_data: Cow::Borrowed(&pkt.clicked_item),
            });

            inv_action_events.send(CreativeInventoryActionEvent {
                client: packet.client,
                slot: pkt.slot,
                clicked_item: pkt.clicked_item,
            });
        }
    }
}

#[derive(Event, Clone, Debug)]
pub struct UpdateSelectedSlotEvent {
    pub client: Entity,
    pub slot: u8,
}

fn handle_update_selected_slot(
    mut packets: EventReader<PacketEvent>,
    mut clients: Query<&mut HeldItem>,
    mut events: EventWriter<UpdateSelectedSlotEvent>,
) {
    for packet in packets.iter() {
        if let Some(pkt) = packet.decode::<UpdateSelectedSlotC2s>() {
            if let Ok(mut held) = clients.get_mut(packet.client) {
                if pkt.slot > 8 {
                    // The client is trying to interact with a slot that does not exist, ignore.
                    continue;
                }
                held.held_item_slot = convert_hotbar_slot_id(pkt.slot as u16);

                events.send(UpdateSelectedSlotEvent {
                    client: packet.client,
                    slot: pkt.slot,
                });
            }
        }
    }
}

/// Convert a slot that is outside a target inventory's range to a slot that is
/// inside the player's inventory.
#[doc(hidden)]
pub fn convert_to_player_slot_id(target_kind: InventoryKind, slot_id: u16) -> u16 {
    // the first slot in the player's general inventory
    let offset = target_kind.slot_count() as u16;
    slot_id - offset + 9
}

fn convert_hotbar_slot_id(slot_id: u16) -> u16 {
    slot_id + PLAYER_INVENTORY_MAIN_SLOTS_COUNT
}

#[derive(Copy, Clone, PartialEq, Eq, Debug)]
pub enum InventoryKind {
    Generic9x1,
    Generic9x2,
    Generic9x3,
    Generic9x4,
    Generic9x5,
    Generic9x6,
    Generic3x3,
    Anvil,
    Beacon,
    BlastFurnace,
    BrewingStand,
    Crafting,
    Enchantment,
    Furnace,
    Grindstone,
    Hopper,
    Lectern,
    Loom,
    Merchant,
    ShulkerBox,
    Smithing,
    Smoker,
    Cartography,
    Stonecutter,
    Player,
}

impl InventoryKind {
    /// The number of slots in this inventory. When the inventory is shown to
    /// clients, this number does not include the player's main inventory slots.
    pub const fn slot_count(self) -> usize {
        match self {
            InventoryKind::Generic9x1 => 9,
            InventoryKind::Generic9x2 => 9 * 2,
            InventoryKind::Generic9x3 => 9 * 3,
            InventoryKind::Generic9x4 => 9 * 4,
            InventoryKind::Generic9x5 => 9 * 5,
            InventoryKind::Generic9x6 => 9 * 6,
            InventoryKind::Generic3x3 => 3 * 3,
            InventoryKind::Anvil => 4,
            InventoryKind::Beacon => 1,
            InventoryKind::BlastFurnace => 3,
            InventoryKind::BrewingStand => 5,
            InventoryKind::Crafting => 10,
            InventoryKind::Enchantment => 2,
            InventoryKind::Furnace => 3,
            InventoryKind::Grindstone => 3,
            InventoryKind::Hopper => 5,
            InventoryKind::Lectern => 1,
            InventoryKind::Loom => 4,
            InventoryKind::Merchant => 3,
            InventoryKind::ShulkerBox => 27,
            InventoryKind::Smithing => 3,
            InventoryKind::Smoker => 3,
            InventoryKind::Cartography => 3,
            InventoryKind::Stonecutter => 2,
            InventoryKind::Player => 46,
        }
    }
}

impl From<InventoryKind> for WindowType {
    fn from(value: InventoryKind) -> Self {
        match value {
            InventoryKind::Generic9x1 => WindowType::Generic9x1,
            InventoryKind::Generic9x2 => WindowType::Generic9x2,
            InventoryKind::Generic9x3 => WindowType::Generic9x3,
            InventoryKind::Generic9x4 => WindowType::Generic9x4,
            InventoryKind::Generic9x5 => WindowType::Generic9x5,
            InventoryKind::Generic9x6 => WindowType::Generic9x6,
            InventoryKind::Generic3x3 => WindowType::Generic3x3,
            InventoryKind::Anvil => WindowType::Anvil,
            InventoryKind::Beacon => WindowType::Beacon,
            InventoryKind::BlastFurnace => WindowType::BlastFurnace,
            InventoryKind::BrewingStand => WindowType::BrewingStand,
            InventoryKind::Crafting => WindowType::Crafting,
            InventoryKind::Enchantment => WindowType::Enchantment,
            InventoryKind::Furnace => WindowType::Furnace,
            InventoryKind::Grindstone => WindowType::Grindstone,
            InventoryKind::Hopper => WindowType::Hopper,
            InventoryKind::Lectern => WindowType::Lectern,
            InventoryKind::Loom => WindowType::Loom,
            InventoryKind::Merchant => WindowType::Merchant,
            InventoryKind::ShulkerBox => WindowType::ShulkerBox,
            InventoryKind::Smithing => WindowType::Smithing,
            InventoryKind::Smoker => WindowType::Smoker,
            InventoryKind::Cartography => WindowType::Cartography,
            InventoryKind::Stonecutter => WindowType::Stonecutter,
            // arbitrarily chosen, because a player inventory technically does not have a window
            // type
            InventoryKind::Player => WindowType::Generic9x4,
        }
    }
}

impl From<WindowType> for InventoryKind {
    fn from(value: WindowType) -> Self {
        match value {
            WindowType::Generic9x1 => InventoryKind::Generic9x1,
            WindowType::Generic9x2 => InventoryKind::Generic9x2,
            WindowType::Generic9x3 => InventoryKind::Generic9x3,
            WindowType::Generic9x4 => InventoryKind::Generic9x4,
            WindowType::Generic9x5 => InventoryKind::Generic9x5,
            WindowType::Generic9x6 => InventoryKind::Generic9x6,
            WindowType::Generic3x3 => InventoryKind::Generic3x3,
            WindowType::Anvil => InventoryKind::Anvil,
            WindowType::Beacon => InventoryKind::Beacon,
            WindowType::BlastFurnace => InventoryKind::BlastFurnace,
            WindowType::BrewingStand => InventoryKind::BrewingStand,
            WindowType::Crafting => InventoryKind::Crafting,
            WindowType::Enchantment => InventoryKind::Enchantment,
            WindowType::Furnace => InventoryKind::Furnace,
            WindowType::Grindstone => InventoryKind::Grindstone,
            WindowType::Hopper => InventoryKind::Hopper,
            WindowType::Lectern => InventoryKind::Lectern,
            WindowType::Loom => InventoryKind::Loom,
            WindowType::Merchant => InventoryKind::Merchant,
            WindowType::ShulkerBox => InventoryKind::ShulkerBox,
            WindowType::Smithing => InventoryKind::Smithing,
            WindowType::Smoker => InventoryKind::Smoker,
            WindowType::Cartography => InventoryKind::Cartography,
            WindowType::Stonecutter => InventoryKind::Stonecutter,
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Resource)]
pub struct InventorySettings {
    pub validate_actions: bool,
}

impl Default for InventorySettings {
    fn default() -> Self {
        Self {
            validate_actions: true,
        }
    }
}

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

    #[test]
    fn test_convert_to_player_slot() {
        assert_eq!(convert_to_player_slot_id(InventoryKind::Generic9x3, 27), 9);
        assert_eq!(convert_to_player_slot_id(InventoryKind::Generic9x3, 36), 18);
        assert_eq!(convert_to_player_slot_id(InventoryKind::Generic9x3, 54), 36);
        assert_eq!(convert_to_player_slot_id(InventoryKind::Generic9x1, 9), 9);
    }

    #[test]
    fn test_convert_hotbar_slot_id() {
        assert_eq!(convert_hotbar_slot_id(0), 36);
        assert_eq!(convert_hotbar_slot_id(4), 40);
        assert_eq!(convert_hotbar_slot_id(8), 44);
    }
}