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
use crate::Server;
use common::{
    comp::{
        agent::{Agent, AgentEvent},
        inventory::{
            item::{tool::AbilityMap, ItemDefinitionIdOwned, MaterialStatManifest},
            Inventory,
        },
    },
    event::ProcessTradeActionEvent,
    trade::{PendingTrade, ReducedInventory, TradeAction, TradeResult, Trades},
};
use common_net::{
    msg::ServerGeneral,
    sync::{Uid, WorldSyncExt},
};
use hashbrown::{hash_map::Entry, HashMap};
use specs::{world::WorldExt, Entity as EcsEntity};
use std::{cmp::Ordering, num::NonZeroU32};
use tracing::{error, trace};
#[cfg(feature = "worldgen")]
use world::IndexOwned;

pub fn notify_agent_simple(
    agents: &mut specs::WriteStorage<Agent>,
    entity: EcsEntity,
    event: AgentEvent,
) {
    if let Some(agent) = agents.get_mut(entity) {
        agent.inbox.push_back(event);
    }
}

#[cfg(feature = "worldgen")]
fn notify_agent_prices(
    mut agents: specs::WriteStorage<Agent>,
    index: &IndexOwned,
    entity: EcsEntity,
    event: AgentEvent,
) {
    if let Some((site_id, agent)) = agents.get_mut(entity).map(|a| (a.behavior.trade_site(), a)) {
        if let AgentEvent::UpdatePendingTrade(boxval) = event {
            // Prefer using this Agent's price data, but use the counterparty's price
            // data if we don't have price data
            let prices = site_id
                .and_then(|site_id| index.get_site_prices(site_id))
                .unwrap_or(boxval.2);
            // Box<(tid, pend, _, inventories)>) = event {
            agent
                .inbox
                .push_back(AgentEvent::UpdatePendingTrade(Box::new((
                    boxval.0, boxval.1, prices, boxval.3,
                ))));
        }
    }
}

/// Invoked when the trade UI is up, handling item changes, accepts, etc
pub(super) fn handle_process_trade_action(
    server: &mut Server,
    ProcessTradeActionEvent(entity, trade_id, action): ProcessTradeActionEvent,
) {
    if let Some(uid) = server.state.ecs().uid_from_entity(entity) {
        let mut trades = server.state.ecs().write_resource::<Trades>();
        if let TradeAction::Decline = action {
            let to_notify = trades.decline_trade(trade_id, uid);
            to_notify
                .and_then(|u| server.state.ecs().entity_from_uid(u))
                .map(|e| {
                    server.notify_client(e, ServerGeneral::FinishedTrade(TradeResult::Declined));
                    notify_agent_simple(
                        &mut server.state.ecs().write_storage(),
                        e,
                        AgentEvent::FinishedTrade(TradeResult::Declined),
                    );
                });
        } else {
            {
                let ecs = server.state.ecs();
                let inventories = ecs.read_component::<Inventory>();
                let get_inventory = |uid: Uid| {
                    if let Some(entity) = ecs.entity_from_uid(uid) {
                        inventories.get(entity)
                    } else {
                        None
                    }
                };
                trades.process_trade_action(trade_id, uid, action, get_inventory);
            }
            if let Entry::Occupied(entry) = trades.trades.entry(trade_id) {
                let parties = entry.get().parties;
                if entry.get().should_commit() {
                    let result = commit_trade(server.state.ecs(), entry.get());
                    entry.remove();
                    for party in parties.iter() {
                        if let Some(e) = server.state.ecs().entity_from_uid(*party) {
                            server.notify_client(e, ServerGeneral::FinishedTrade(result.clone()));
                            notify_agent_simple(
                                &mut server.state.ecs().write_storage(),
                                e,
                                AgentEvent::FinishedTrade(result.clone()),
                            );
                        }
                        trades.entity_trades.remove_entry(party);
                    }
                } else {
                    let mut entities: [Option<specs::Entity>; 2] = [None, None];
                    let mut inventories: [Option<ReducedInventory>; 2] = [None, None];
                    #[cfg(feature = "worldgen")]
                    let mut prices = None;
                    #[cfg(not(feature = "worldgen"))]
                    let prices = None;
                    let agents = server.state.ecs().read_storage::<Agent>();
                    // sadly there is no map and collect on arrays
                    for i in 0..2 {
                        // parties.len()) {
                        entities[i] = server.state.ecs().entity_from_uid(parties[i]);
                        if let Some(e) = entities[i] {
                            inventories[i] = server
                                .state
                                .ecs()
                                .read_component::<Inventory>()
                                .get(e)
                                .map(ReducedInventory::from);
                            // Get price info from the first Agent in the trade (currently, an
                            // Agent will never initiate a trade with another agent though)
                            #[cfg(feature = "worldgen")]
                            {
                                prices = prices.or_else(|| {
                                    agents
                                        .get(e)
                                        .and_then(|a| a.behavior.trade_site())
                                        .and_then(|id| server.index.get_site_prices(id))
                                });
                            }
                        }
                    }
                    drop(agents);
                    for party in entities.iter() {
                        if let Some(e) = *party {
                            server.notify_client(
                                e,
                                ServerGeneral::UpdatePendingTrade(
                                    trade_id,
                                    entry.get().clone(),
                                    prices.clone(),
                                ),
                            );
                            #[cfg(feature = "worldgen")]
                            notify_agent_prices(
                                server.state.ecs().write_storage::<Agent>(),
                                &server.index,
                                e,
                                AgentEvent::UpdatePendingTrade(Box::new((
                                    trade_id,
                                    entry.get().clone(),
                                    prices.clone().unwrap_or_default(),
                                    inventories.clone(),
                                ))),
                            );
                        }
                    }
                }
            }
        }
    }
}

/// Cancel all trades registered for a given UID.
///
/// Note: This doesn't send any notification to the provided entity (only other
/// participants in the trade). It is assumed that the supplied entity either no
/// longer exists or is awareof this cancellation through other means (e.g.
/// client getting ExitInGameSuccess message knows that it should clear any
/// trades).
pub(crate) fn cancel_trades_for(state: &mut common_state::State, entity: EcsEntity) {
    let ecs = state.ecs();
    if let Some(uid) = ecs.uid_from_entity(entity) {
        let mut trades = ecs.write_resource::<Trades>();

        let active_trade = match trades.entity_trades.get(&uid) {
            Some(n) => *n,
            None => return,
        };

        let to_notify = trades.decline_trade(active_trade, uid);
        to_notify.and_then(|u| ecs.entity_from_uid(u)).map(|e| {
            if let Some(c) = ecs.read_storage::<crate::Client>().get(e) {
                c.send_fallible(ServerGeneral::FinishedTrade(TradeResult::Declined));
            }
            notify_agent_simple(
                &mut ecs.write_storage::<Agent>(),
                e,
                AgentEvent::FinishedTrade(TradeResult::Declined),
            );
        });
    }
}

/// Commit a trade that both parties have agreed to, modifying their respective
/// inventories
fn commit_trade(ecs: &specs::World, trade: &PendingTrade) -> TradeResult {
    let mut entities = Vec::new();
    for party in trade.parties.iter() {
        match ecs.entity_from_uid(*party) {
            Some(entity) => entities.push(entity),
            None => return TradeResult::Declined,
        }
    }
    let mut inventories = ecs.write_storage::<Inventory>();
    for entity in entities.iter() {
        if inventories.get_mut(*entity).is_none() {
            return TradeResult::Declined;
        }
    }
    let invmsg = "inventories.get_mut(entities[who]).is_none() should have returned already";
    trace!("committing trade: {:?}", trade);
    // Compute the net change in slots of each player during the trade, to detect
    // out-of-space-ness before transferring any items
    let mut delta_slots: [i64; 2] = [0, 0];

    // local struct used to calculate delta_slots for stackable items.
    // Uses u128 as an intermediate value to prevent overflow.
    #[derive(Default)]
    struct ItemQuantities {
        full_stacks: u64,
        quantity_sold: u128,
        freed_capacity: u128,
        unusable_capacity: u128,
    }

    // local struct used to calculate delta_slots for stackable items
    struct TradeQuantities {
        max_stack_size: u32,
        trade_quantities: [ItemQuantities; 2],
    }

    impl TradeQuantities {
        fn new(max_stack_size: u32) -> Self {
            Self {
                max_stack_size,
                trade_quantities: [ItemQuantities::default(), ItemQuantities::default()],
            }
        }
    }

    // Hashmap to compute merged stackable stacks, including overflow checks
    let mut stackable_items: HashMap<ItemDefinitionIdOwned, TradeQuantities> = HashMap::new();
    for who in [0, 1].iter().cloned() {
        for (slot, quantity) in trade.offers[who].iter() {
            let inventory = inventories.get_mut(entities[who]).expect(invmsg);
            let item = match inventory.get(*slot) {
                Some(item) => item,
                None => {
                    error!(
                        "PendingTrade invariant violation in trade {:?}: slots offered in a trade \
                         should be non-empty",
                        trade
                    );
                    return TradeResult::Declined;
                },
            };

            // assuming the quantity is never 0
            match item.amount().cmp(quantity) {
                Ordering::Less => {
                    error!(
                        "PendingTrade invariant violation in trade {:?}: party {} offered more of \
                         an item than they have",
                        trade, who
                    );
                    return TradeResult::Declined;
                },
                Ordering::Equal => {
                    if item.is_stackable() {
                        // Marks a full stack to remove. Can no longer accept items from the other
                        // party, and therefore adds the remaining capacity it holds to
                        // `unusable_capacity`.
                        let TradeQuantities {
                            max_stack_size,
                            trade_quantities,
                        } = stackable_items
                            .entry(item.item_definition_id().to_owned())
                            .or_insert_with(|| TradeQuantities::new(item.max_amount()));

                        trade_quantities[who].full_stacks += 1;
                        trade_quantities[who].quantity_sold += *quantity as u128;
                        trade_quantities[who].unusable_capacity +=
                            *max_stack_size as u128 - item.amount() as u128;
                    } else {
                        delta_slots[who] -= 1; // exact, removes the whole stack
                        delta_slots[1 - who] += 1; // item is not stackable, so the stacks won't merge
                    }
                },
                Ordering::Greater => {
                    if item.is_stackable() {
                        // Marks a partial stack to remove, able to accepts items from the other
                        // party, and therefore adds the additional capacity freed after the item
                        // exchange to `freed_capacity`.
                        let TradeQuantities {
                            max_stack_size: _,
                            trade_quantities,
                        } = stackable_items
                            .entry(item.item_definition_id().to_owned())
                            .or_insert_with(|| TradeQuantities::new(item.max_amount()));

                        trade_quantities[who].quantity_sold += *quantity as u128;
                        trade_quantities[who].freed_capacity += *quantity as u128;
                    } else {
                        // unreachable in theory
                        error!(
                            "Inventory invariant violation in trade {:?}: party {} has a stack \
                             larger than 1 of an unstackable item",
                            trade, who
                        );
                        return TradeResult::Declined;
                    }
                },
            }
        }
    }
    // at this point delta_slots only contains the slot variations for unstackable
    // items. The following loops calculates capacity for stackable items and
    // computes the final delta_slots in consequence.

    for (
        item_id,
        TradeQuantities {
            max_stack_size,
            trade_quantities,
        },
    ) in stackable_items.iter()
    {
        for who in [0, 1].iter().cloned() {
            // removes all exchanged full stacks.
            delta_slots[who] -= trade_quantities[who].full_stacks as i64;

            // calculates the available item capacity in the other party's inventory,
            // substracting the unusable space calculated previously,
            // and adding the capacity freed by the trade.
            let other_party_capacity = inventories
                .get_mut(entities[1 - who])
                .expect(invmsg)
                .slots()
                .flatten()
                .filter_map(|it| {
                    if it.item_definition_id() == item_id.as_ref() {
                        Some(*max_stack_size as u128 - it.amount() as u128)
                    } else {
                        None
                    }
                })
                .sum::<u128>()
                - trade_quantities[1 - who].unusable_capacity
                + trade_quantities[1 - who].freed_capacity;

            // checks if the capacity in remaining partial stacks of the other party is
            // enough to contain everything, creates more stacks otherwise
            if other_party_capacity < trade_quantities[who].quantity_sold {
                let surplus = trade_quantities[who].quantity_sold - other_party_capacity;
                // the total amount of exchanged slots can never exceed the max inventory size
                // (around 4 * 2^32 slots), so the cast to i64 should be safe
                delta_slots[1 - who] += (surplus / *max_stack_size as u128) as i64 + 1;
            }
        }
    }

    trace!("delta_slots: {:?}", delta_slots);
    for who in [0, 1].iter().cloned() {
        // Inventories should never exceed 2^{63} slots, so the usize -> i64
        // conversions here should be safe
        let inv = inventories.get_mut(entities[who]).expect(invmsg);
        if inv.populated_slots() as i64 + delta_slots[who] > inv.capacity() as i64 {
            return TradeResult::NotEnoughSpace;
        }
    }

    let mut items = [Vec::new(), Vec::new()];
    let ability_map = ecs.read_resource::<AbilityMap>();
    let msm = ecs.read_resource::<MaterialStatManifest>();
    for who in [0, 1].iter().cloned() {
        for (slot, quantity) in trade.offers[who].iter() {
            if let Some(quantity) = NonZeroU32::new(*quantity) {
                if let Some(item) = inventories
                    .get_mut(entities[who])
                    .expect(invmsg)
                    .take_amount(*slot, quantity, &ability_map, &msm)
                {
                    items[who].push(item);
                }
            }
        }
    }

    for who in [0, 1].iter().cloned() {
        if let Err(leftovers) = inventories
            .get_mut(entities[1 - who])
            .expect(invmsg)
            .push_all(items[who].drain(..))
        {
            // This should only happen if the arithmetic above for delta_slots says there's
            // enough space and there isn't (i.e. underapproximates)
            panic!(
                "Not enough space for all the items, leftovers are {:?}",
                leftovers
            );
        }
    }

    TradeResult::Completed
}

#[cfg(test)]
mod tests {
    use hashbrown::HashMap;

    use super::*;
    use common::{comp::slot::InvSlotId, uid::IdMaps};

    use specs::{Builder, World};

    // Creates a specs World containing two Entities which have Inventory
    // components. Left over inventory size is determined by input. Mapping to the
    // returned Entities. Any input over the maximum default inventory size will
    // result in maximum left over space.
    fn create_mock_trading_world(
        player_inv_size: usize,
        merchant_inv_size: usize,
    ) -> (World, EcsEntity, EcsEntity) {
        let mut mockworld = World::new();
        mockworld.insert(IdMaps::new());
        mockworld.insert(MaterialStatManifest::load().cloned());
        mockworld.insert(AbilityMap::load().cloned());
        mockworld.register::<Inventory>();
        mockworld.register::<Uid>();

        let player: EcsEntity = mockworld
            .create_entity()
            .with(Inventory::with_empty())
            .build();

        let merchant: EcsEntity = mockworld
            .create_entity()
            .with(Inventory::with_empty())
            .build();

        {
            let mut uids = mockworld.write_component::<Uid>();
            let mut id_maps = mockworld.write_resource::<IdMaps>();
            uids.insert(player, id_maps.allocate(player))
                .expect("inserting player uid failed");
            uids.insert(merchant, id_maps.allocate(merchant))
                .expect("inserting merchant uid failed");
        }

        let invmsg = "inventories.get_mut().is_none() should have returned already";
        let capmsg = "There should be enough space here";
        let mut inventories = mockworld.write_component::<Inventory>();
        let mut playerinv = inventories.get_mut(player).expect(invmsg);
        if player_inv_size < playerinv.capacity() {
            for _ in player_inv_size..playerinv.capacity() {
                playerinv
                    .push(common::comp::Item::new_from_asset_expect(
                        "common.items.npc_armor.pants.plate_red",
                    ))
                    .expect(capmsg);
            }
        }

        let mut merchantinv = inventories.get_mut(merchant).expect(invmsg);
        if merchant_inv_size < merchantinv.capacity() {
            for _ in merchant_inv_size..merchantinv.capacity() {
                merchantinv
                    .push(common::comp::Item::new_from_asset_expect(
                        "common.items.armor.cloth_purple.foot",
                    ))
                    .expect(capmsg);
            }
        }
        drop(inventories);

        (mockworld, player, merchant)
    }

    fn prepare_merchant_inventory(mockworld: &World, merchant: EcsEntity) {
        let mut inventories = mockworld.write_component::<Inventory>();
        let invmsg = "inventories.get_mut().is_none() should have returned already";
        let capmsg = "There should be enough space here";
        let mut merchantinv = inventories.get_mut(merchant).expect(invmsg);
        for _ in 0..10 {
            merchantinv
                .push(common::comp::Item::new_from_asset_expect(
                    "common.items.consumable.potion_minor",
                ))
                .expect(capmsg);
            merchantinv
                .push(common::comp::Item::new_from_asset_expect(
                    "common.items.food.meat.fish_cooked",
                ))
                .expect(capmsg);
        }
        drop(inventories);
    }

    #[test]
    fn commit_trade_with_stackable_item_test() {
        use common::{assets::AssetExt, comp::item::ItemDef};
        use std::sync::Arc;

        let (mockworld, player, merchant) = create_mock_trading_world(1, 20);

        prepare_merchant_inventory(&mockworld, merchant);

        let invmsg = "inventories.get_mut().is_none() should have returned already";
        let capmsg = "There should be enough space here";
        let mut inventories = mockworld.write_component::<Inventory>();

        let mut playerinv = inventories.get_mut(player).expect(invmsg);
        playerinv
            .push(common::comp::Item::new_from_asset_expect(
                "common.items.consumable.potion_minor",
            ))
            .expect(capmsg);

        let potion_asset = "common.items.consumable.potion_minor";

        let potion = common::comp::Item::new_from_asset_expect(potion_asset);
        let potion_def = Arc::<ItemDef>::load_expect_cloned(potion_asset);

        let merchantinv = inventories.get_mut(merchant).expect(invmsg);

        let potioninvid = merchantinv
            .get_slot_of_item(&potion)
            .expect("expected get_slot_of_item to return");

        let playerid = mockworld
            .uid_from_entity(player)
            .expect("mockworld.uid_from_entity(player) should have returned");
        let merchantid = mockworld
            .uid_from_entity(merchant)
            .expect("mockworld.uid_from_entity(player) should have returned");

        let playeroffers: HashMap<InvSlotId, u32> = HashMap::new();
        let mut merchantoffers: HashMap<InvSlotId, u32> = HashMap::new();
        merchantoffers.insert(potioninvid, 1);

        let trade = PendingTrade {
            parties: [playerid, merchantid],
            accept_flags: [true, true],
            offers: [playeroffers, merchantoffers],
            phase: common::trade::TradePhase::Review,
        };

        drop(inventories);

        let traderes = commit_trade(&mockworld, &trade);
        assert_eq!(traderes, TradeResult::Completed);

        let mut inventories = mockworld.write_component::<Inventory>();
        let playerinv = inventories.get_mut(player).expect(invmsg);
        let potioncount = playerinv.item_count(&potion_def);
        assert_eq!(potioncount, 2);
    }

    #[test]
    fn commit_trade_with_full_inventory_test() {
        let (mockworld, player, merchant) = create_mock_trading_world(1, 20);

        prepare_merchant_inventory(&mockworld, merchant);

        let invmsg = "inventories.get_mut().is_none() should have returned already";
        let capmsg = "There should be enough space here";
        let mut inventories = mockworld.write_component::<Inventory>();

        let mut playerinv = inventories.get_mut(player).expect(invmsg);
        playerinv
            .push(common::comp::Item::new_from_asset_expect(
                "common.items.consumable.potion_minor",
            ))
            .expect(capmsg);

        let fish = common::comp::Item::new_from_asset_expect("common.items.food.meat.fish_cooked");
        let merchantinv = inventories.get_mut(merchant).expect(invmsg);

        let fishinvid = merchantinv
            .get_slot_of_item(&fish)
            .expect("expected get_slot_of_item to return");

        let playerid = mockworld
            .uid_from_entity(player)
            .expect("mockworld.uid_from_entity(player) should have returned");
        let merchantid = mockworld
            .uid_from_entity(merchant)
            .expect("mockworld.uid_from_entity(player) should have returned");

        let playeroffers: HashMap<InvSlotId, u32> = HashMap::new();
        let mut merchantoffers: HashMap<InvSlotId, u32> = HashMap::new();
        merchantoffers.insert(fishinvid, 1);
        let trade = PendingTrade {
            parties: [playerid, merchantid],
            accept_flags: [true, true],
            offers: [playeroffers, merchantoffers],
            phase: common::trade::TradePhase::Review,
        };

        drop(inventories);

        let traderes = commit_trade(&mockworld, &trade);
        assert_eq!(traderes, TradeResult::NotEnoughSpace);
    }

    #[test]
    fn commit_trade_with_empty_inventory_test() {
        let (mockworld, player, merchant) = create_mock_trading_world(20, 20);

        prepare_merchant_inventory(&mockworld, merchant);

        let invmsg = "inventories.get_mut().is_none() should have returned already";
        let mut inventories = mockworld.write_component::<Inventory>();

        let fish = common::comp::Item::new_from_asset_expect("common.items.food.meat.fish_cooked");
        let merchantinv = inventories.get_mut(merchant).expect(invmsg);

        let fishinvid = merchantinv
            .get_slot_of_item(&fish)
            .expect("expected get_slot_of_item to return");

        let playerid = mockworld
            .uid_from_entity(player)
            .expect("mockworld.uid_from_entity(player) should have returned");
        let merchantid = mockworld
            .uid_from_entity(merchant)
            .expect("mockworld.uid_from_entity(player) should have returned");

        let playeroffers: HashMap<InvSlotId, u32> = HashMap::new();
        let mut merchantoffers: HashMap<InvSlotId, u32> = HashMap::new();
        merchantoffers.insert(fishinvid, 1);
        let trade = PendingTrade {
            parties: [playerid, merchantid],
            accept_flags: [true, true],
            offers: [playeroffers, merchantoffers],
            phase: common::trade::TradePhase::Review,
        };

        drop(inventories);

        let traderes = commit_trade(&mockworld, &trade);
        assert_eq!(traderes, TradeResult::Completed);
    }

    #[test]
    fn commit_trade_with_both_full_inventories_test() {
        let (mockworld, player, merchant) = create_mock_trading_world(2, 2);

        prepare_merchant_inventory(&mockworld, merchant);

        let invmsg = "inventories.get_mut().is_none() should have returned already";
        let capmsg = "There should be enough space here";
        let mut inventories = mockworld.write_component::<Inventory>();

        let fish = common::comp::Item::new_from_asset_expect("common.items.food.meat.fish_cooked");
        let merchantinv = inventories.get_mut(merchant).expect(invmsg);
        let fishinvid = merchantinv
            .get_slot_of_item(&fish)
            .expect("expected get_slot_of_item to return");

        let potion =
            common::comp::Item::new_from_asset_expect("common.items.consumable.potion_minor");
        let mut playerinv = inventories.get_mut(player).expect(invmsg);
        playerinv
            .push(common::comp::Item::new_from_asset_expect(
                "common.items.consumable.potion_minor",
            ))
            .expect(capmsg);
        let potioninvid = playerinv
            .get_slot_of_item(&potion)
            .expect("expected get_slot_of_item to return");

        let playerid = mockworld
            .uid_from_entity(player)
            .expect("mockworld.uid_from_entity(player) should have returned");
        let merchantid = mockworld
            .uid_from_entity(merchant)
            .expect("mockworld.uid_from_entity(player) should have returned");

        let mut playeroffers: HashMap<InvSlotId, u32> = HashMap::new();
        playeroffers.insert(potioninvid, 1);

        let mut merchantoffers: HashMap<InvSlotId, u32> = HashMap::new();
        merchantoffers.insert(fishinvid, 10);
        let trade = PendingTrade {
            parties: [playerid, merchantid],
            accept_flags: [true, true],
            offers: [playeroffers, merchantoffers],
            phase: common::trade::TradePhase::Review,
        };

        drop(inventories);

        let traderes = commit_trade(&mockworld, &trade);
        assert_eq!(traderes, TradeResult::Completed);
    }

    #[test]
    fn commit_trade_with_overflow() {
        let (mockworld, player, merchant) = create_mock_trading_world(2, 20);

        prepare_merchant_inventory(&mockworld, merchant);

        let invmsg = "inventories.get_mut().is_none() should have returned already";
        let capmsg = "There should be enough space here";
        let mut inventories = mockworld.write_component::<Inventory>();

        let mut playerinv = inventories.get_mut(player).expect(invmsg);
        let mut potion =
            common::comp::Item::new_from_asset_expect("common.items.consumable.potion_minor");
        potion
            .set_amount(potion.max_amount() - 2)
            .expect("Should be below the max amount");
        playerinv.push(potion).expect(capmsg);

        let potion =
            common::comp::Item::new_from_asset_expect("common.items.consumable.potion_minor");
        let merchantinv = inventories.get_mut(merchant).expect(invmsg);

        let potioninvid = merchantinv
            .get_slot_of_item(&potion)
            .expect("expected get_slot_of_item to return");

        let playerid = mockworld
            .uid_from_entity(player)
            .expect("mockworld.uid_from_entity(player) should have returned");
        let merchantid = mockworld
            .uid_from_entity(merchant)
            .expect("mockworld.uid_from_entity(player) should have returned");

        let playeroffers: HashMap<InvSlotId, u32> = HashMap::new();
        let mut merchantoffers: HashMap<InvSlotId, u32> = HashMap::new();
        merchantoffers.insert(potioninvid, 10);
        let trade = PendingTrade {
            parties: [playerid, merchantid],
            accept_flags: [true, true],
            offers: [playeroffers, merchantoffers],
            phase: common::trade::TradePhase::Review,
        };

        drop(inventories);

        let traderes = commit_trade(&mockworld, &trade);
        assert_eq!(traderes, TradeResult::Completed);

        let mut inventories = mockworld.write_component::<Inventory>();
        let mut playerinv = inventories.get_mut(player).expect(invmsg);

        let slot1 = playerinv
            .get_slot_of_item(&potion)
            .expect("There should be a slot here");
        let item1 = playerinv
            .remove(slot1)
            .expect("The slot should not be empty");

        let slot2 = playerinv
            .get_slot_of_item(&potion)
            .expect("There should be a slot here");
        let item2 = playerinv
            .remove(slot2)
            .expect("The slot should not be empty");

        assert_eq!(item1.amount(), potion.max_amount());
        assert_eq!(item2.amount(), 8);
    }

    #[test]
    fn commit_trade_with_inventory_overflow_failure() {
        let (mockworld, player, merchant) = create_mock_trading_world(2, 20);

        prepare_merchant_inventory(&mockworld, merchant);

        let invmsg = "inventories.get_mut().is_none() should have returned already";
        let capmsg = "There should be enough space here";
        let mut inventories = mockworld.write_component::<Inventory>();

        let mut playerinv = inventories.get_mut(player).expect(invmsg);
        let mut potion =
            common::comp::Item::new_from_asset_expect("common.items.consumable.potion_minor");
        potion
            .set_amount(potion.max_amount() - 2)
            .expect("Should be below the max amount");
        playerinv.push(potion).expect(capmsg);
        let mut potion =
            common::comp::Item::new_from_asset_expect("common.items.consumable.potion_minor");
        potion
            .set_amount(potion.max_amount() - 2)
            .expect("Should be below the max amount");
        playerinv.push(potion).expect(capmsg);

        let potion =
            common::comp::Item::new_from_asset_expect("common.items.consumable.potion_minor");
        let merchantinv = inventories.get_mut(merchant).expect(invmsg);

        let potioninvid = merchantinv
            .get_slot_of_item(&potion)
            .expect("expected get_slot_of_item to return");

        let playerid = mockworld
            .uid_from_entity(player)
            .expect("mockworld.uid_from_entity(player) should have returned");
        let merchantid = mockworld
            .uid_from_entity(merchant)
            .expect("mockworld.uid_from_entity(player) should have returned");

        let playeroffers: HashMap<InvSlotId, u32> = HashMap::new();
        let mut merchantoffers: HashMap<InvSlotId, u32> = HashMap::new();
        merchantoffers.insert(potioninvid, 5);
        let trade = PendingTrade {
            parties: [playerid, merchantid],
            accept_flags: [true, true],
            offers: [playeroffers, merchantoffers],
            phase: common::trade::TradePhase::Review,
        };

        drop(inventories);

        let traderes = commit_trade(&mockworld, &trade);
        assert_eq!(traderes, TradeResult::NotEnoughSpace);
    }

    #[test]
    fn commit_trade_with_inventory_overflow_success() {
        let (mockworld, player, merchant) = create_mock_trading_world(2, 20);

        prepare_merchant_inventory(&mockworld, merchant);

        let invmsg = "inventories.get_mut().is_none() should have returned already";
        let capmsg = "There should be enough space here";
        let mut inventories = mockworld.write_component::<Inventory>();

        let mut playerinv = inventories.get_mut(player).expect(invmsg);
        let mut potion =
            common::comp::Item::new_from_asset_expect("common.items.consumable.potion_minor");
        potion
            .set_amount(potion.max_amount() - 2)
            .expect("Should be below the max amount");
        playerinv.push(potion).expect(capmsg);
        let mut potion =
            common::comp::Item::new_from_asset_expect("common.items.consumable.potion_minor");
        potion
            .set_amount(potion.max_amount() - 2)
            .expect("Should be below the max amount");
        playerinv.push(potion).expect(capmsg);

        let potion =
            common::comp::Item::new_from_asset_expect("common.items.consumable.potion_minor");
        let merchantinv = inventories.get_mut(merchant).expect(invmsg);

        let potioninvid = merchantinv
            .get_slot_of_item(&potion)
            .expect("expected get_slot_of_item to return");

        let playerid = mockworld
            .uid_from_entity(player)
            .expect("mockworld.uid_from_entity(player) should have returned");
        let merchantid = mockworld
            .uid_from_entity(merchant)
            .expect("mockworld.uid_from_entity(player) should have returned");

        let playeroffers: HashMap<InvSlotId, u32> = HashMap::new();
        let mut merchantoffers: HashMap<InvSlotId, u32> = HashMap::new();
        merchantoffers.insert(potioninvid, 4);
        let trade = PendingTrade {
            parties: [playerid, merchantid],
            accept_flags: [true, true],
            offers: [playeroffers, merchantoffers],
            phase: common::trade::TradePhase::Review,
        };

        drop(inventories);

        let traderes = commit_trade(&mockworld, &trade);
        assert_eq!(traderes, TradeResult::Completed);
    }
}