weasel 0.11.0

A customizable battle system for turn-based games.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
//! Event module.

use crate::battle::{Battle, BattleRules, BattleState, Version};
use crate::error::{WeaselError, WeaselResult};
use crate::player::PlayerId;
use crate::team::TeamId;
use crate::user::UserEventId;
use log::error;
#[cfg(feature = "serialization")]
use serde::{Deserialize, Serialize};
use std::any::Any;
use std::fmt::{Debug, Formatter, Result};
use std::marker::PhantomData;
use std::ops::{Deref, Range};

/// Type for the id of events.
pub type EventId = u32;

/// Enum to represent all different kinds of events.
// Internal note: remember to update the event debug and serialization tests in tests/event.rs
// each time a new event is added to weasel.
#[derive(Copy, Clone, PartialEq, Debug)]
pub enum EventKind {
    /// Dummy event doing nothing.
    DummyEvent,
    /// Create a new team.
    CreateTeam,
    /// Create a new creature.
    CreateCreature,
    /// Create a new object.
    CreateObject,
    /// Move an entity from one position to another.
    MoveEntity,
    /// Start a new turn.
    StartTurn,
    /// End the current turn.
    EndTurn,
    /// End the current round.
    EndRound,
    /// Perform a turn for the environment.
    EnvironmentTurn,
    /// Activate an actor's ability.
    ActivateAbility,
    /// Invoke a team's power.
    InvokePower,
    /// Apply the consequences of an impact on the world.
    ApplyImpact,
    /// Modify the statistics of a character.
    AlterStatistics,
    /// Modify the statuses of a character.
    AlterStatuses,
    /// Modify the abilities of an actor.
    AlterAbilities,
    /// Modify the powers of a team.
    AlterPowers,
    /// Regenerate the statistics of a character.
    RegenerateStatistics,
    /// Regenerate the abilities of an actor.
    RegenerateAbilities,
    /// Regenerate the powers of a team.
    RegeneratePowers,
    /// Inflict a status effect on a character.
    InflictStatus,
    /// Frees a character from a status effect.
    ClearStatus,
    /// Convert a creature from one team to another.
    ConvertCreature,
    /// Set new relations between teams.
    SetRelations,
    /// An event to set a team's objectives outcome.
    ConcludeObjectives,
    /// Remove a creature from the battle.
    RemoveCreature,
    /// Remove an object from the battle.
    RemoveObject,
    /// Remove a team from the battle.
    RemoveTeam,
    /// Modify the spatial model.
    AlterSpace,
    /// Reset the entropy model.
    ResetEntropy,
    /// Reset the objectives of a team.
    ResetObjectives,
    /// Reset the rounds model.
    ResetRounds,
    /// Reset the space model.
    ResetSpace,
    /// End the battle.
    EndBattle,
    /// A user defined event with an unique id.
    UserEvent(UserEventId),
}

/// Types of access rights that might be required in order to fire an event.
pub enum EventRights<'a, R: BattleRules> {
    /// Everyone can fire the event.
    None,
    /// Only the server can fire the event.
    Server,
    /// Only the server or a player with rights to this team can fire the event.
    Team(&'a TeamId<R>),
    /// Only the server or a player with rights to all of these teams can fire the event.
    Teams(Vec<&'a TeamId<R>>),
}

impl<'a, R: BattleRules> Debug for EventRights<'a, R> {
    fn fmt(&self, f: &mut Formatter<'_>) -> Result {
        use EventRights::*;
        match self {
            None => write!(f, "EventRights::None"),
            Server => write!(f, "EventRights::Server"),
            Team(id) => write!(f, "EventRights::Team {{ {:?} }}", id),
            Teams(ids) => write!(f, "EventRights::Teams {{ {:?} }}", ids),
        }
    }
}

impl<'a, 'b, R: BattleRules> PartialEq<EventRights<'b, R>> for EventRights<'a, R> {
    fn eq(&self, other: &EventRights<'b, R>) -> bool {
        use EventRights::*;
        match (self, other) {
            (None, None) => true,
            (Server, Server) => true,
            (Team(a), Team(b)) => a == b,
            (Teams(a), Teams(b)) => a == b,
            _ => false,
        }
    }
}

impl<'a, R: BattleRules> Eq for EventRights<'a, R> {}

/// An event is the only mean to apply a change to the world.
pub trait Event<R: BattleRules>: Debug {
    /// Verifies if this event can be applied to the world.
    fn verify(&self, battle: &Battle<R>) -> WeaselResult<(), R>;

    /// Applies this event to the world. This method is called only if `verify` succeeded.
    ///
    /// If there's a failure inside this method, it immediately panic because we can't guarantee
    /// any consistency in the state of the world.
    ///
    /// Events generated by this event are stored into `queue`, if there's one.
    /// Noe that they will keep a link with the original event.
    fn apply(&self, battle: &mut Battle<R>, queue: &mut Option<EventQueue<R>>);

    /// Returns the kind of this event.
    fn kind(&self) -> EventKind;

    /// Clones this event as a trait object.
    fn box_clone(&self) -> Box<dyn Event<R> + Send>;

    /// Returns an `Any` reference this event.
    fn as_any(&self) -> &dyn Any;

    /// Returns the access rights required by this event.
    ///
    /// The provided implementation returns `EventRights::Server`.
    fn rights<'a>(&'a self, _battle: &'a Battle<R>) -> EventRights<'a, R> {
        EventRights::Server
    }
}

impl<R: BattleRules> Clone for Box<dyn Event<R> + Send> {
    fn clone(&self) -> Box<dyn Event<R> + Send> {
        self.box_clone()
    }
}

impl<R: BattleRules> PartialEq<Box<dyn Event<R> + Send>> for Box<dyn Event<R> + Send> {
    fn eq(&self, other: &Box<dyn Event<R> + Send>) -> bool {
        self.kind() == other.kind()
    }
}

/// A wrapper to decorate verified events with additional data.
pub struct EventWrapper<R: BattleRules> {
    /// Event Id is assigned only after events has been verified for consistency.
    id: EventId,
    /// Id of the event that generated this one.
    origin: Option<EventId>,
    /// The actual event wrapped inside this struct.
    pub(crate) event: Box<dyn Event<R> + Send>,
}

impl<R: BattleRules> Clone for EventWrapper<R> {
    fn clone(&self) -> Self {
        Self::new(self.id, self.origin, self.event.clone())
    }
}

impl<R: BattleRules> EventWrapper<R> {
    /// Creates a new EventWrapper.
    pub(crate) fn new(
        id: EventId,
        origin: Option<EventId>,
        event: Box<dyn Event<R> + Send>,
    ) -> Self {
        Self { id, origin, event }
    }

    /// Returns this event's id.
    pub fn id(&self) -> EventId {
        self.id
    }

    /// Returns the id of the event that caused this one.
    pub fn origin(&self) -> Option<EventId> {
        self.origin
    }

    /// Returns the event.
    #[allow(clippy::borrowed_box)]
    pub fn event(&self) -> &Box<dyn Event<R> + Send> {
        &self.event
    }

    /// Consume this event wrapper and returns a versioned instance of it.
    pub fn version(self, version: Version<R>) -> VersionedEventWrapper<R> {
        VersionedEventWrapper::new(self, version)
    }
}

impl<R: BattleRules> Deref for EventWrapper<R> {
    type Target = Box<dyn Event<R> + Send>;

    fn deref(&self) -> &Self::Target {
        &self.event
    }
}

/// Decorates an `EventWrapper` with the battle rules version.
pub struct VersionedEventWrapper<R: BattleRules> {
    pub(crate) wrapper: EventWrapper<R>,
    pub(crate) version: Version<R>,
}

impl<R: BattleRules> Clone for VersionedEventWrapper<R> {
    fn clone(&self) -> Self {
        Self::new(self.wrapper.clone(), self.version.clone())
    }
}

impl<R: BattleRules> VersionedEventWrapper<R> {
    /// Creates a new VersionedEventWrapper.
    pub(crate) fn new(wrapper: EventWrapper<R>, version: Version<R>) -> Self {
        Self { wrapper, version }
    }

    /// Returns the `EventWrapper` contained in this object.
    pub fn wrapper(&self) -> &EventWrapper<R> {
        &self.wrapper
    }

    /// Returns the `BattleRules`' version of the event.
    pub fn version(&self) -> &Version<R> {
        &self.version
    }
}

impl<R: BattleRules> Deref for VersionedEventWrapper<R> {
    type Target = EventWrapper<R>;

    fn deref(&self) -> &Self::Target {
        &self.wrapper
    }
}

/// Function that tells if an event prototype met its additional conditions
/// in order to be applied.
pub type Condition<R> = std::rc::Rc<dyn Fn(&BattleState<R>) -> bool>;

/// A prototype for tentative events that are not yet verified.
pub struct EventPrototype<R: BattleRules> {
    /// Id of the event that generated this one.
    origin: Option<EventId>,
    /// The actual event wrapped inside this struct.
    event: Box<dyn Event<R> + Send>,
    /// Condition that must be satisfied for this prototype to be valid.
    condition: Option<Condition<R>>,
}

impl<R: BattleRules> EventPrototype<R> {
    /// Creates a new EventPrototype.
    pub(crate) fn new(event: Box<dyn Event<R> + Send>) -> Self {
        Self {
            origin: None,
            event,
            condition: None,
        }
    }

    pub(crate) fn promote(self, id: EventId) -> EventWrapper<R> {
        EventWrapper::new(id, self.origin, self.event)
    }

    /// Returns the id of the event that caused this one.
    pub fn origin(&self) -> Option<EventId> {
        self.origin
    }

    /// Sets the origin of this prototype.
    pub fn set_origin(&mut self, origin: Option<EventId>) {
        self.origin = origin;
    }

    /// Returns the event.
    #[allow(clippy::borrowed_box)]
    pub fn event(&self) -> &Box<dyn Event<R> + Send> {
        &self.event
    }

    /// Returns the prototype's acceptance condition.
    pub fn condition(&self) -> &Option<Condition<R>> {
        &self.condition
    }

    /// Sets the acceptance condition of this prototype.
    pub fn set_condition(&mut self, condition: Option<Condition<R>>) {
        self.condition = condition;
    }

    /// Consume this event prototype and returns a `ClientEventPrototype` instance of it.
    pub fn client_prototype(
        self,
        version: Version<R>,
        player: Option<PlayerId>,
    ) -> ClientEventPrototype<R> {
        ClientEventPrototype::new(self.origin, self.event, version, player)
    }
}

impl<R: BattleRules> Deref for EventPrototype<R> {
    type Target = Box<dyn Event<R> + Send>;

    fn deref(&self) -> &Self::Target {
        &self.event
    }
}

impl<R: BattleRules> Clone for EventPrototype<R> {
    fn clone(&self) -> Self {
        Self {
            origin: self.origin,
            event: self.event.clone(),
            condition: self.condition.clone(),
        }
    }
}

/// An event prototype sent by a client to a server that must be first verified
/// before being processed.
pub struct ClientEventPrototype<R: BattleRules> {
    /// Id of the event that generated this one.
    origin: Option<EventId>,
    /// The actual event wrapped inside this struct.
    pub(crate) event: Box<dyn Event<R> + Send>,
    /// Version of `BattleRules` that generated this event.
    pub(crate) version: Version<R>,
    /// Id of the player who fired this event.
    player: Option<PlayerId>,
}

impl<R: BattleRules> ClientEventPrototype<R> {
    /// Creates a new ClientEventPrototype.
    pub(crate) fn new(
        origin: Option<EventId>,
        event: Box<dyn Event<R> + Send>,
        version: Version<R>,
        player: Option<PlayerId>,
    ) -> Self {
        Self {
            origin,
            event,
            version,
            player,
        }
    }

    /// Returns the `BattleRules`'s version of the event.
    pub fn version(&self) -> &Version<R> {
        &self.version
    }

    /// Returns the id of the event that caused this one.
    pub fn origin(&self) -> Option<EventId> {
        self.origin
    }

    /// Returns the event.
    #[allow(clippy::borrowed_box)]
    pub fn event(&self) -> &Box<dyn Event<R> + Send> {
        &self.event
    }

    /// Transforms this client event into an event prototype.
    pub(crate) fn prototype(self) -> EventPrototype<R> {
        EventPrototype {
            origin: self.origin,
            event: self.event,
            condition: None,
        }
    }

    /// Authenticate this event with the identity of `player`.
    ///
    /// **Note:** you can use this method to perform server-side authentication of events coming
    /// from a remote client.
    pub fn authenticate(&mut self, player: PlayerId) {
        self.player = Some(player);
    }

    /// Returns the player who fired this prototype.
    pub fn player(&self) -> Option<PlayerId> {
        self.player
    }
}

impl<R: BattleRules> Deref for ClientEventPrototype<R> {
    type Target = Box<dyn Event<R> + Send>;

    fn deref(&self) -> &Self::Target {
        &self.event
    }
}

impl<R: BattleRules> Clone for ClientEventPrototype<R> {
    fn clone(&self) -> Self {
        Self {
            origin: self.origin,
            event: self.event.clone(),
            version: self.version.clone(),
            player: self.player,
        }
    }
}

/// A trait to describe an output type from an event processor.
/// The requirement of this type is to be able to return an object for an ok state.
pub trait DefaultOutput<R: BattleRules> {
    /// Error type for this `DefaultOutput`.
    type Error: Sized + PartialEq + Debug;
    /// Returns the `ok` result for this type.
    fn ok() -> Self;
    /// Convert this output into an `Option`.
    fn err(self) -> Option<Self::Error>;
    /// Convert this output into a `WeaselResult`.
    fn result(self) -> WeaselResult<(), R>;
}

/// A trait for objects that can process new local events.
pub trait EventProcessor<R: BattleRules> {
    /// Return type for this processor's `process()`.
    type ProcessOutput: DefaultOutput<R>;

    /// Processes a local event prototype.
    fn process(&mut self, event: EventPrototype<R>) -> Self::ProcessOutput;
}

/// A trait for objects that can verify and process new client events.
pub trait EventServer<R: BattleRules> {
    /// Processes a client event prototype.
    fn process_client(&mut self, event: ClientEventPrototype<R>) -> WeaselResult<(), R>;
}

/// A trait for objects that can receive verified events.
pub trait EventReceiver<R: BattleRules> {
    /// Processes a verified event.
    fn receive(&mut self, event: VersionedEventWrapper<R>) -> WeaselResult<(), R>;
}

/// Trait to unify the interface of all event builders.
pub trait EventTrigger<'a, R: BattleRules, P: 'a + EventProcessor<R>> {
    /// Returns the processor bound to this trigger.
    fn processor(&'a mut self) -> &'a mut P;

    /// Returns the event constructed by this builder.
    fn event(&self) -> Box<dyn Event<R> + Send>;

    /// Fires the event constructed by this builder.
    fn fire(&'a mut self) -> P::ProcessOutput {
        let prototype = self.prototype();
        self.processor().process(prototype)
    }

    /// Returns the event constructed by this builder, wrapped in a prototype.
    fn prototype(&self) -> EventPrototype<R> {
        EventPrototype::new(self.event())
    }
}

/// Collection to queue events prototypes, in order of insertion.
pub type EventQueue<R> = Vec<EventPrototype<R>>;

// Implement `EventProcessor` for event queues, so that it can be possible to
// use the latter with event triggers.
impl<R: BattleRules> EventProcessor<R> for EventQueue<R> {
    type ProcessOutput = ();

    fn process(&mut self, event: EventPrototype<R>) -> Self::ProcessOutput {
        self.push(event);
    }
}

/// An event that does nothing.
///
/// # Examples
/// ```
/// use weasel::{
///     battle_rules, event::DummyEvent, rules::empty::*, Battle, BattleController, BattleRules,
///     EventKind, EventTrigger, Server,
/// };
///
/// battle_rules! {}
///
/// let battle = Battle::builder(CustomRules::new()).build();
/// let mut server = Server::builder(battle).build();
///
/// DummyEvent::trigger(&mut server).fire().unwrap();
/// assert_eq!(
///     server.battle().history().events()[0].kind(),
///     EventKind::DummyEvent
/// );
/// ```
#[cfg_attr(feature = "serialization", derive(Serialize, Deserialize))]
pub struct DummyEvent<R> {
    #[cfg_attr(feature = "serialization", serde(skip))]
    _phantom: PhantomData<R>,
}

impl<R: BattleRules> DummyEvent<R> {
    /// Returns a trigger for this event.
    pub fn trigger<P: EventProcessor<R>>(processor: &mut P) -> DummyEventTrigger<R, P> {
        DummyEventTrigger {
            processor,
            _phantom: PhantomData,
        }
    }
}

impl<R> Debug for DummyEvent<R> {
    fn fmt(&self, f: &mut Formatter<'_>) -> Result {
        write!(f, "DummyEvent {{ }}")
    }
}

impl<R> Clone for DummyEvent<R> {
    fn clone(&self) -> Self {
        Self {
            _phantom: PhantomData,
        }
    }
}

impl<R: BattleRules + 'static> Event<R> for DummyEvent<R> {
    fn verify(&self, _: &Battle<R>) -> WeaselResult<(), R> {
        Ok(())
    }

    fn apply(&self, _: &mut Battle<R>, _: &mut Option<EventQueue<R>>) {}

    fn kind(&self) -> EventKind {
        EventKind::DummyEvent
    }

    fn box_clone(&self) -> Box<dyn Event<R> + Send> {
        Box::new(self.clone())
    }

    fn as_any(&self) -> &dyn Any {
        self
    }

    fn rights<'a>(&'a self, _battle: &'a Battle<R>) -> EventRights<'a, R> {
        EventRights::None
    }
}

/// Trigger to build and fire a `DummyEvent` event.
pub struct DummyEventTrigger<'a, R, P>
where
    R: BattleRules,
    P: EventProcessor<R>,
{
    processor: &'a mut P,
    _phantom: PhantomData<R>,
}

impl<'a, R, P> EventTrigger<'a, R, P> for DummyEventTrigger<'a, R, P>
where
    R: BattleRules + 'static,
    P: EventProcessor<R>,
{
    fn processor(&'a mut self) -> &'a mut P {
        self.processor
    }

    /// Returns a `DummyEvent` event.
    fn event(&self) -> Box<dyn Event<R> + Send> {
        Box::new(DummyEvent {
            _phantom: PhantomData,
        })
    }
}

// Implement `EventProcessor` for option, so that it would be possible to pass
// None or a real processor to event triggers.
impl<R, T> EventProcessor<R> for &mut Option<T>
where
    R: BattleRules,
    T: EventProcessor<R>,
{
    type ProcessOutput = T::ProcessOutput;

    fn process(&mut self, event: EventPrototype<R>) -> Self::ProcessOutput {
        if let Some(processor) = self {
            processor.process(event)
        } else {
            Self::ProcessOutput::ok()
        }
    }
}

impl<R, T> EventProcessor<R> for Option<T>
where
    R: BattleRules,
    T: EventProcessor<R>,
{
    type ProcessOutput = T::ProcessOutput;

    fn process(&mut self, event: EventPrototype<R>) -> Self::ProcessOutput {
        if let Some(processor) = self {
            processor.process(event)
        } else {
            Self::ProcessOutput::ok()
        }
    }
}

// Implement `EventProcessor` for (), doing nothing.
impl<R> EventProcessor<R> for ()
where
    R: BattleRules,
{
    type ProcessOutput = WeaselResult<(), R>;

    fn process(&mut self, _: EventPrototype<R>) -> Self::ProcessOutput {
        Err(WeaselError::EmptyEventProcessor)
    }
}

impl<R: BattleRules> DefaultOutput<R> for () {
    type Error = ();

    fn ok() -> Self {}

    fn err(self) -> Option<Self::Error> {
        None
    }

    fn result(self) -> WeaselResult<(), R> {
        Ok(())
    }
}

/// Decorator for `EventQueue` processor. It appends new events at the front of the queue, instead
/// of pushing them at the back.
///
/// # Examples
/// ```
/// use weasel::{
///     battle_rules, event::DummyEvent, event::Prioritized, rules::empty::*, BattleRules,
///     EndBattle, EventKind, EventQueue, EventTrigger,
/// };
///
/// battle_rules! {}
///
/// let mut queue = EventQueue::<CustomRules>::new();
/// EndBattle::trigger(&mut queue).fire();
/// DummyEvent::trigger(&mut Prioritized::new(&mut queue)).fire();
/// assert_eq!(queue[0].kind(), EventKind::DummyEvent);
/// assert_eq!(queue[1].kind(), EventKind::EndBattle);
/// ```
pub struct Prioritized<'a, R: BattleRules> {
    event_queue: &'a mut EventQueue<R>,
}

impl<'a, R: BattleRules> Prioritized<'a, R> {
    /// Creates a new Prioritized decorator for the given `event_queue`.
    pub fn new(event_queue: &'a mut EventQueue<R>) -> Self {
        Self { event_queue }
    }
}

impl<R> EventProcessor<R> for Prioritized<'_, R>
where
    R: BattleRules,
{
    type ProcessOutput = ();

    fn process(&mut self, event: EventPrototype<R>) -> Self::ProcessOutput {
        self.event_queue.insert(0, event);
    }
}

/// Decorator for `EventQueue` processor. It sets the origin of all events inserted into the queue
/// to the `EventId` specified during instantiation, unless origin has been manually specified.
///
/// # Examples
/// ```
/// use weasel::{
///     battle_rules, event::DummyEvent, rules::empty::*, BattleRules, EndBattle, EventKind,
///     EventQueue, EventTrigger, LinkedQueue,
/// };
///
/// battle_rules! {}
///
/// let mut queue = EventQueue::<CustomRules>::new();
/// let origin = 42;
/// DummyEvent::trigger(&mut LinkedQueue::new(&mut queue, Some(origin))).fire();
/// assert_eq!(queue[0].origin(), Some(origin));
/// ```
pub struct LinkedQueue<'a, R: BattleRules> {
    event_queue: &'a mut EventQueue<R>,
    origin: Option<EventId>,
}

impl<'a, R: BattleRules> LinkedQueue<'a, R> {
    /// Creates a new LinkedQueue decorator for the given `event_queue`.
    pub fn new(event_queue: &'a mut EventQueue<R>, origin: Option<EventId>) -> Self {
        Self {
            event_queue,
            origin,
        }
    }
}

impl<R> EventProcessor<R> for LinkedQueue<'_, R>
where
    R: BattleRules,
{
    type ProcessOutput = ();

    fn process(&mut self, mut event: EventPrototype<R>) -> Self::ProcessOutput {
        if event.origin().is_none() {
            event.set_origin(self.origin);
        }
        self.event_queue.push(event);
    }
}

/// Decorator for event triggers to add a condition on the generated event prototype.
///
/// # Examples
/// ```
/// use weasel::{
///     battle_rules, event::Conditional, event::DummyEvent, rules::empty::*, Battle, BattleRules,
///     BattleState, EventTrigger, Server, WeaselError,
/// };
///
/// battle_rules! {}
///
/// let battle = Battle::builder(CustomRules::new()).build();
/// let mut server = Server::builder(battle).build();
///
/// let result = Conditional::new(
///     DummyEvent::trigger(&mut server),
///     std::rc::Rc::new(|state: &BattleState<CustomRules>| {
///         state
///             .entities()
///             .teams()
///             .count() == 42
///     }),
/// )
/// .fire();
/// assert_eq!(
///     result.err().map(|e| e.unfold()),
///     Some(WeaselError::ConditionUnsatisfied)
/// );
/// ```
pub struct Conditional<'a, R, T, P>
where
    R: BattleRules,
    T: EventTrigger<'a, R, P>,
    P: 'a + EventProcessor<R>,
{
    trigger: T,
    condition: Condition<R>,
    _phantom: PhantomData<&'a P>,
}

impl<'a, R, T, P> Conditional<'a, R, T, P>
where
    R: BattleRules,
    T: EventTrigger<'a, R, P>,
    P: 'a + EventProcessor<R>,
    Condition<R>: Clone,
{
    /// Creates a new `Conditional` decorator for an `EventTrigger`.
    pub fn new(trigger: T, condition: Condition<R>) -> Self {
        Self {
            trigger,
            condition,
            _phantom: PhantomData,
        }
    }
}

impl<'a, R, T, P> EventTrigger<'a, R, P> for Conditional<'a, R, T, P>
where
    R: BattleRules,
    T: EventTrigger<'a, R, P>,
    P: 'a + EventProcessor<R>,
    Condition<R>: Clone,
{
    fn processor(&'a mut self) -> &'a mut P {
        self.trigger.processor()
    }

    fn event(&self) -> Box<dyn Event<R> + Send> {
        self.trigger.event()
    }

    fn prototype(&self) -> EventPrototype<R> {
        let mut prototype = self.trigger.prototype();
        prototype.set_condition(Some(self.condition.clone()));
        prototype
    }
}

/// Id of an event sink.
pub type EventSinkId = u16;

/// Basic trait for event sinks.
pub trait EventSink {
    /// Returns the Id associated to this sink.
    fn id(&self) -> EventSinkId;

    /// Invoked when this sink is forcedly disconnected.
    ///
    /// The provided implementation does nothing.
    fn on_disconnect(&mut self) {}
}

/// An output sink to dump versioned and verified events to a client.
pub trait ClientSink<R: BattleRules>: EventSink {
    /// Sends an already accepted event to a remote or local client.
    fn send(&mut self, event: &VersionedEventWrapper<R>) -> WeaselResult<(), R>;
}

/// An output sink to dump tentative events to a server.
pub trait ServerSink<R: BattleRules>: EventSink {
    /// Sends a client event prototype to a remote or local server.
    fn send(&mut self, event: &ClientEventPrototype<R>) -> WeaselResult<(), R>;
}

/// A data structure to contain multiple client sinks.
pub(crate) struct MultiClientSink<R: BattleRules> {
    sinks: Vec<Box<dyn ClientSink<R> + Send>>,
}

impl<R: BattleRules> MultiClientSink<R> {
    pub(crate) fn new() -> Self {
        Self { sinks: Vec::new() }
    }

    /// Adds a new sink.
    /// Returns an error if another sink with the same id already exists.
    fn add(&mut self, sink: Box<dyn ClientSink<R> + Send>) -> WeaselResult<(), R> {
        if self.sinks.iter().any(|e| e.id() == sink.id()) {
            Err(WeaselError::DuplicatedEventSink(sink.id()))
        } else {
            self.sinks.push(sink);
            Ok(())
        }
    }

    /// Sends all `events` to an existing sink.
    /// Returns an error if sending the events failed or the sink doesn't exist.
    fn send<I>(&mut self, id: EventSinkId, events: I) -> WeaselResult<(), R>
    where
        I: Iterator<Item = VersionedEventWrapper<R>>,
    {
        let index = self.sinks.iter().position(|e| e.id() == id);
        if let Some(index) = index {
            // Send events.
            for event in events {
                let sink = &mut self.sinks[index];
                let result = sink.send(&event);
                if result.is_err() {
                    sink.on_disconnect();
                    self.sinks.remove(index);
                }
                result?;
            }
            Ok(())
        } else {
            Err(WeaselError::EventSinkNotFound(id))
        }
    }

    /// Removes the sink with the given `id`, if it exists.
    fn remove(&mut self, id: EventSinkId) {
        let index = self.sinks.iter().position(|e| e.id() == id);
        if let Some(index) = index {
            self.sinks.remove(index);
        }
    }

    /// Sends an event to all sinks.
    /// If a sink returns an error, its on_disconnect() fn will be invoked
    /// and the sink is disconnected from the server.
    pub(crate) fn send_all(&mut self, event: &VersionedEventWrapper<R>) {
        let mut failed_sinks_index = Vec::new();
        for (i, sink) in self.sinks.iter_mut().enumerate() {
            sink.send(event).unwrap_or_else(|err| {
                error!("{:?}", err);
                failed_sinks_index.push(i)
            });
        }
        for i in failed_sinks_index {
            self.sinks[i].on_disconnect();
            self.sinks.remove(i);
        }
    }

    fn sinks(&self) -> impl Iterator<Item = &Box<dyn ClientSink<R> + Send>> {
        self.sinks.iter()
    }
}

/// A structure to access client sinks.
pub struct MultiClientSinkHandle<'a, R>
where
    R: BattleRules,
{
    sinks: &'a MultiClientSink<R>,
}

impl<'a, R> MultiClientSinkHandle<'a, R>
where
    R: BattleRules + 'static,
{
    pub(crate) fn new(sinks: &'a MultiClientSink<R>) -> Self {
        Self { sinks }
    }

    /// Returns an iterator over all sinks.
    pub fn sinks(&self) -> impl Iterator<Item = &Box<dyn ClientSink<R> + Send>> {
        self.sinks.sinks()
    }
}

/// A structure to access and manipulate client sinks.
pub struct MultiClientSinkHandleMut<'a, R>
where
    R: BattleRules + 'static,
{
    sinks: &'a mut MultiClientSink<R>,
    battle: &'a Battle<R>,
}

impl<'a, R> MultiClientSinkHandleMut<'a, R>
where
    R: BattleRules + 'static,
{
    pub(crate) fn new(sinks: &'a mut MultiClientSink<R>, battle: &'a Battle<R>) -> Self {
        Self { sinks, battle }
    }

    /// Adds a new sink.
    ///
    /// Sinks must have unique ids.
    pub fn add_sink(&mut self, sink: Box<dyn ClientSink<R> + Send>) -> WeaselResult<(), R> {
        self.sinks.add(sink)
    }

    /// Adds a new sink and shares the battle history with it,
    /// starting from the event having `event_id` up to the most recent event.
    ///
    /// Sinks must have unique ids.
    pub fn add_sink_from(
        &mut self,
        sink: Box<dyn ClientSink<R> + Send>,
        event_id: EventId,
    ) -> WeaselResult<(), R> {
        self.add_sink_range(
            sink,
            Range {
                start: event_id,
                end: self.battle.history().len(),
            },
        )
    }

    /// Adds a new sink and shares a portion of the battle history with it.
    /// More precisely, only the events inside `range` will be sent to the sink.
    ///
    /// Sinks must have unique ids.
    pub fn add_sink_range(
        &mut self,
        sink: Box<dyn ClientSink<R> + Send>,
        range: Range<EventId>,
    ) -> WeaselResult<(), R> {
        let range = normalize_range(range, self.battle.history().len())?;
        // Add the new sink.
        let sink_id = sink.id();
        self.sinks.add(sink)?;
        // Get all versioned events from history and send them.
        self.sinks
            .send(sink_id, self.battle.versioned_events(range))
    }

    /// Sends a range of events from the battle history to the sink with the given id.
    pub fn send_range(&mut self, id: EventSinkId, range: Range<EventId>) -> WeaselResult<(), R> {
        let range = normalize_range(range, self.battle.history().len())?;
        // Get all versioned events from history and send them.
        self.sinks.send(id, self.battle.versioned_events(range))
    }

    /// Removes the sink with the given id.
    pub fn remove_sink(&mut self, id: EventSinkId) {
        self.sinks.remove(id);
    }

    /// Returns an iterator over all sinks.
    pub fn sinks(&self) -> impl Iterator<Item = &Box<dyn ClientSink<R> + Send>> {
        self.sinks.sinks()
    }
}

/// Converts a range of `EventId` into a range of `usize`.
fn normalize_range<R: BattleRules>(
    range: Range<EventId>,
    history_len: EventId,
) -> WeaselResult<Range<usize>, R> {
    if range.start > range.end || range.end > history_len {
        return Err(WeaselError::InvalidEventRange(range, history_len));
    }
    let range: Range<usize> = Range {
        start: range.start as usize,
        end: range.end as usize,
    };
    Ok(range)
}

/// Decorator for event triggers to manually set the origin of an event.
///
/// # Examples
/// ```
/// use weasel::{
///     battle_rules, event::DummyEvent, event::Originated, rules::empty::*, Battle,
///     BattleController, BattleRules, EventTrigger, Server,
/// };
///
/// battle_rules! {}
///
/// let battle = Battle::builder(CustomRules::new()).build();
/// let mut server = Server::builder(battle).build();
///
/// Originated::new(DummyEvent::trigger(&mut server), 42)
///     .fire()
///     .unwrap();
/// assert_eq!(server.battle().history().events()[0].origin(), Some(42));
/// ```
pub struct Originated<'a, R, T, P>
where
    R: BattleRules,
    T: EventTrigger<'a, R, P>,
    P: 'a + EventProcessor<R>,
{
    trigger: T,
    origin: EventId,
    _phantom: PhantomData<&'a P>,
    _phantom_: PhantomData<R>,
}

impl<'a, R, T, P> Originated<'a, R, T, P>
where
    R: BattleRules,
    T: EventTrigger<'a, R, P>,
    P: 'a + EventProcessor<R>,
{
    /// Creates a new decorator to change an event's origin.
    pub fn new(trigger: T, origin: EventId) -> Self {
        Self {
            trigger,
            origin,
            _phantom: PhantomData,
            _phantom_: PhantomData,
        }
    }
}

impl<'a, R, T, P> EventTrigger<'a, R, P> for Originated<'a, R, T, P>
where
    R: BattleRules,
    T: EventTrigger<'a, R, P>,
    P: 'a + EventProcessor<R>,
{
    fn processor(&'a mut self) -> &'a mut P {
        self.trigger.processor()
    }

    fn event(&self) -> Box<dyn Event<R> + Send> {
        self.trigger.event()
    }

    fn prototype(&self) -> EventPrototype<R> {
        let mut prototype = self.trigger.prototype();
        prototype.set_origin(Some(self.origin));
        prototype
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::entropy::ResetEntropy;
    use crate::{battle_rules, rules::empty::*};
    use std::iter::once;

    battle_rules! {}

    #[test]
    fn event_equality() {
        let dummy = DummyEvent::<CustomRules>::trigger(&mut ()).event();
        let dummy_copy = dummy.clone();
        let reset_entropy = ResetEntropy::<CustomRules>::trigger(&mut ()).event();
        assert_eq!(&dummy, &dummy_copy);
        assert_ne!(&dummy, &reset_entropy);
    }

    #[test]
    fn multi_client_sink() {
        struct Sink {
            id: EventSinkId,
            ok: bool,
        }

        impl EventSink for Sink {
            fn id(&self) -> EventSinkId {
                self.id
            }
        }

        impl ClientSink<CustomRules> for Sink {
            fn send(
                &mut self,
                _: &VersionedEventWrapper<CustomRules>,
            ) -> WeaselResult<(), CustomRules> {
                if self.ok {
                    Ok(())
                } else {
                    Err(WeaselError::EventSinkError("broken".to_string()))
                }
            }
        }

        // Check add.
        let mut multi = MultiClientSink::new();
        assert_eq!(multi.add(Box::new(Sink { id: 0, ok: true })).err(), None);
        assert_eq!(multi.sinks.len(), 1);
        assert_eq!(
            multi.add(Box::new(Sink { id: 0, ok: true })).err(),
            Some(WeaselError::DuplicatedEventSink(0))
        );
        assert_eq!(multi.sinks.len(), 1);
        // Check remove.
        multi.remove(2);
        assert_eq!(multi.sinks.len(), 1);
        multi.remove(0);
        assert_eq!(multi.sinks.len(), 0);
        // Check send_all.
        assert_eq!(multi.add(Box::new(Sink { id: 0, ok: true })).err(), None);
        assert_eq!(multi.add(Box::new(Sink { id: 1, ok: false })).err(), None);
        assert_eq!(multi.sinks.len(), 2);
        let event = DummyEvent::<CustomRules>::trigger(&mut ())
            .prototype()
            .promote(0)
            .version(0);
        multi.send_all(&event);
        assert_eq!(multi.sinks.len(), 1);
        // Check send.
        assert_eq!(multi.send(0, once(event.clone())).err(), None);
        assert_eq!(
            multi.send(2, once(event.clone())).err(),
            Some(WeaselError::EventSinkNotFound(2))
        );
        assert_eq!(multi.add(Box::new(Sink { id: 1, ok: false })).err(), None);
        assert_eq!(multi.sinks.len(), 2);
        assert_eq!(
            multi.send(1, once(event)).err(),
            Some(WeaselError::EventSinkError("broken".to_string()))
        );
        assert_eq!(multi.sinks.len(), 1);
    }

    #[test]
    #[allow(clippy::let_unit_value)]
    fn decorators_stack() {
        let mut processor = ();
        let event = Conditional::new(
            DummyEvent::trigger(&mut processor),
            std::rc::Rc::new(|_: &BattleState<CustomRules>| true),
        );
        let event = Originated::new(event, 0);
        let prototype = event.prototype();
        assert!(prototype.condition.is_some());
        assert!(prototype.origin.is_some());
    }

    #[test]
    fn linked_queue_respects_origin() {
        let mut queue = EventQueue::<CustomRules>::new();
        let origin = 42;
        let mut linked_queue = LinkedQueue::new(&mut queue, Some(origin + 1));
        Originated::new(DummyEvent::trigger(&mut linked_queue), origin).fire();
        assert_eq!(queue[0].origin(), Some(origin));
    }

    #[test]
    fn basic_event_rights_equality() {
        type R = CustomRules;
        use EventRights::*;
        assert_eq!(EventRights::<R>::None, None);
        assert_ne!(EventRights::<R>::None, Team(&1));
        assert_ne!(EventRights::<R>::None, Teams(vec![&1]));
        assert_eq!(EventRights::<R>::Server, Server);
        assert_ne!(EventRights::<R>::Server, Team(&1));
        assert_ne!(EventRights::<R>::Server, Teams(vec![&1]));
        assert_eq!(EventRights::<R>::Team(&1), Team(&1));
        assert_ne!(EventRights::<R>::Team(&1), Team(&2));
        assert_eq!(EventRights::<R>::Teams(vec![&1, &2]), Teams(vec![&1, &2]));
        assert_ne!(EventRights::<R>::Teams(vec![&1, &2]), Teams(vec![&1, &3]));
        assert_ne!(EventRights::<R>::Team(&1), Teams(vec![&1]));
    }
}